-
Notifications
You must be signed in to change notification settings - Fork 0
/
observable-array.js
73 lines (49 loc) · 1.74 KB
/
observable-array.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
66
67
68
69
70
71
72
73
var ObservableArray = (function() {
var arrProto = Array.prototype;
/*
constructor
*/
function ObservableArray(collection) {
// calling with `new` is optional
if (!(this instanceof ObservableArray)) {
return new ObservableArray(collection);
}
// add items from passed `collection` to `this`
collection = collection || [];
for (var i = 0; i < collection.length; i++) {
this[i] = collection[i];
}
// set length so it acts like an array: http://stackoverflow.com/a/6599447/552067
this.length = collection.length;
// keep list of observing functions for subscribable.js
this.subscribers = {};
}
/*
make changes observable via subscribable.js
*/
ObservableArray.prototype = new Subscribable();
/*
methods from Array.prototype that modify `this`
*/
var modifyingMethods = 'pop push shift unshift splice reverse sort'.split(' ');
// add *clones* of the above native array methods to ObservableArray.prototype
// the clones should notify observers after completion
modifyingMethods.forEach(function(methodName) {
var method = arrProto[methodName];
ObservableArray.prototype[methodName] = function() {
var returnValue = method.apply(this, arguments);
var args = [methodName].concat(arrProto.slice.call(arguments));
this.trigger.apply(this, args);
return returnValue;
};
});
/*
methods from Array.prototype that don't modify `this`
*/
var returningMethods = 'slice concat join some every forEach map filter reduce reduceRight indexOf lastIndexOf toString toLocaleString'.split(' ');
// add the above native array methods to ObservableArray.prototype
returningMethods.forEach(function(methodName) {
ObservableArray.prototype[methodName] = arrProto[methodName];
});
return ObservableArray;
})();