-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patharray_model.js
52 lines (39 loc) · 1.03 KB
/
array_model.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
var Emitter = require('component-emitter');
var ArrayModel = function(Type, init, parent) {
if (!(this instanceof ArrayModel)) {
return new ArrayModel(Type, init, parent);
}
var self = this;
Array.call(this);
self._Type = Type;
if (init) {
init.forEach(self.push.bind(self));
}
Object.defineProperty(self, '_parent', {
get: function() {
return parent;
}
})
};
ArrayModel.prototype = new Array();
Emitter(ArrayModel.prototype);
ArrayModel.prototype.toJSON = function() {
return this.map(function(val) {
return val.toJSON ? val.toJSON() : val;
});
};
ArrayModel.prototype.push = function(obj) {
var self = this;
var val = self._Type(obj);
if (typeof val === 'object') {
Object.defineProperty(val, 'parent', {
get: function() {
return self._parent;
}
});
}
Array.prototype.push.call(self, val);
self.emit('add', val);
return val;
};
module.exports = ArrayModel;