-
Notifications
You must be signed in to change notification settings - Fork 0
/
lazyObject.js
46 lines (39 loc) · 1.44 KB
/
lazyObject.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
var lazyObject = function() {
var deferreds = {};
// Result returning
return {
with: function(keys, callback, scope) {
if (!_.isString(keys) && !_.isArray(keys)) {
throw new Error('Error in lazyObject.with(): first argument should be a string or an array!');
}
if (!_.isFunction(callback)) {
throw new Error('Error in lazyObject.with(): second argument should be a function!');
}
keys = _.isString(keys) ? [ keys ] : keys
var deferredValues = _.map(keys, function(key) {
if (!deferreds[key]) {
deferreds[key] = deferred();
}
return deferreds[key];
});
when.apply(null, deferredValues).done(function() {
callback.apply(scope, arguments);
});
},
set: function(key, value) {
if (!_.isString(key) && !_.isObject(key)) {
throw new Error('Error in lazyObject.set(): first argument should be a string or an object!');
}
if (_.isObject(key)) {
_.each(key, function(value, k) {
this.set(k, value);
}, this);
} else {
if (!deferreds[key]) {
deferreds[key] = deferred();
}
deferreds[key].resolve(value);
}
}
};
}