-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone.factotum.js
63 lines (47 loc) · 1.48 KB
/
backbone.factotum.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
(function (factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
window.Backbone = window.Backbone || {};
window.Backbone.Factotum = factory();
}
}(function() {
'use strict';
const Factory = function(factoryOpts = {}) {
const { klass, attrs } = factoryOpts;
return Object.create({
klass,
attrs,
create(numberOfItems, opts) {
return Array.apply(null, Array(numberOfItems)).map(() => {
const evaluatedAttrs = Object.keys(this.attrs).reduce((h, key) => {
const attr = this.attrs[key];
h[key] = typeof attr === 'function' ? attr.call(this) : attr;
return h;
}, {});
return new this.klass(evaluatedAttrs, opts);
});
}
});
};
return Object.create({
factories: {},
sequence(callback) {
let counter = 0;
return () => callback.call(this, counter++);
},
reset() {
this.factories = {};
},
define(name, klass, attrs = {}) {
this.factories[name] = Factory({ klass, attrs });
},
create(name, numberOfItems = 1, opts = {}) {
if (typeof numberOfItems === 'object') { // if the second parameter is an object
[opts, numberOfItems] = [numberOfItems, 1]; // we assume they are omitting 'numberOfItems'
}
const items = this.factories[name].create(numberOfItems, opts);
return numberOfItems > 1 ? items : items.shift();
}
});
}));