-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
65 lines (54 loc) · 1.53 KB
/
index.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
64
65
try {
var clone = require('clone');
var each = require('each');
var type = require('type');
} catch (e) {
var clone = require('clone-component');
var each = require('each-component');
var type = require('component-type');
}
var is = require('is');
/**
* Plugin.
*
* @param {Function|Object} values The default values dictionary or the Model.
*/
module.exports = function (values) {
if ('object' === type(values)) {
return function (Model) {
bind(Model, values);
};
} else {
return bind(values);
}
};
/**
* Bind to the model's construct event.
*
* @param {Function} Model The model constructor.
*/
function bind (Model, defaults) {
defaults || (defaults = {});
Model.on('construct', function (model, attrs) {
each(Model.attrs, function (key, options) {
var value = undefined != options.default
? options.default
: defaults[key];
if (value !== undefined) apply(model, key, value);
});
});
}
/**
* Default a `model` with a `value` for a `key` if it doesn't exist. Use a clone
* of the value if it is not passed from a function, so that it's
* easy to declare objects and arrays without worrying about copying by reference.
*
* @param {Model} model The model.
* @param {String} key The key to back by a default.
* @param {Mixed|Function} value The default value to use.
*/
function apply (model, key, value) {
if(model[key]() !== undefined) return;
value = is.function(value) ? value.call(model) : clone(value);
model.attrs[key] = value;
}