forked from jdarling/Object.observe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObject.observe.poly.js
255 lines (243 loc) · 8.27 KB
/
Object.observe.poly.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/*
Tested against Chromium build with Object.observe and acts EXACTLY the same,
though Chromium build is MUCH faster
Trying to stay as close to the spec as possible,
this is a work in progress, feel free to comment/update
Specification:
http://wiki.ecmascript.org/doku.php?id=harmony:observe
Built using parts of:
https://github.com/tvcutsem/harmony-reflect/blob/master/examples/observer.js
Limits so far;
Built using polling... Will update again with polling/getter&setters to make things better at some point
*/
"use strict";
if(!Object.observe){
(function(extend, global){
var isCallable = (function(toString){
var s = toString.call(toString),
u = typeof u;
return typeof global.alert === "object" ?
function(f){
return s === toString.call(f) || (!!f && typeof f.toString == u && typeof f.valueOf == u && /^\s*\bfunction\b/.test("" + f));
}:
function(f){
return s === toString.call(f);
}
;
})(extend.prototype.toString);
var isNumeric=function(n){
return !isNaN(parseFloat(n)) && isFinite(n);
};
var sameValue = function(x, y){
if(x===y){
return x !== 0 || 1 / x === 1 / y;
}
return x !== x && y !== y;
};
var isAccessorDescriptor = function(desc){
if (typeof(desc) === 'undefined'){
return false;
}
return ('get' in desc || 'set' in desc);
};
var isDataDescriptor = function(desc){
if (typeof(desc) === 'undefined'){
return false;
}
return ('value' in desc || 'writable' in desc);
};
var validateArguments = function(O, callback){
if(typeof(O)!=='object'){
// Throw Error
throw new TypeError("Object.observeObject called on non-object");
}
if(isCallable(callback)===false){
// Throw Error
throw new TypeError("Object.observeObject: Expecting function");
}
if(Object.isFrozen(callback)===true){
// Throw Error
throw new TypeError("Object.observeObject: Expecting unfrozen function");
}
};
var Observer = (function(){
var wraped = [];
var Observer = function(O, callback){
validateArguments(O, callback);
Object.getNotifier(O).addListener(callback);
if(wraped.indexOf(O)===-1){
wraped.push(O);
}else{
Object.getNotifier(O)._checkPropertyListing();
}
};
Observer.prototype.deliverChangeRecords = function(O){
Object.getNotifier(O).deliverChangeRecords();
};
wraped.lastScanned = 0;
var f = (function(wrapped){
return function(){
var i = 0, l = wrapped.length, startTime = new Date(), takingTooLong=false;
for(i=wrapped.lastScanned; (i<l)&&(!takingTooLong); i++){
Object.getNotifier(wrapped[i])._checkPropertyListing();
takingTooLong=((new Date())-startTime)>100; // make sure we don't take more than 100 milliseconds to scan all objects
}
wrapped.lastScanned=i<l?i:0; // reset wrapped so we can make sure that we pick things back up
setTimeout(f, 100);
};
})(wraped);
setTimeout(f, 100);
return Observer;
})();
var Notifier = function(watching){
var _listeners = [], _updates = [], _updater = false, properties = [], values = [];
var self = this;
Object.defineProperty(self, '_watching', {
get: (function(watched){
return function(){
return watched;
};
})(watching)
});
var wrapProperty = function(object, prop){
var propType = typeof(object[prop]), descriptor = Object.getOwnPropertyDescriptor(object, prop);
if((prop==='getNotifier')||isAccessorDescriptor(descriptor)||(!descriptor.enumerable)){
return false;
}
if((object instanceof Array)&&isNumeric(prop)){
var idx = properties.length;
properties[idx] = prop;
values[idx] = object[prop];
return true;
}
(function(idx, prop){
properties[idx] = prop;
values[idx] = object[prop];
Object.defineProperty(object, prop, {
get: function(){
return values[idx];
},
set: function(value){
if(!sameValue(values[idx], value)){
Object.getNotifier(object).queueUpdate(object, prop, 'updated', values[idx]);
values[idx] = value;
}
}
});
})(properties.length, prop);
return true;
};
self._checkPropertyListing = function(dontQueueUpdates){
var object = self._watching, keys = Object.keys(object), i=0, l=keys.length;
var newKeys = [], oldKeys = properties.slice(0), updates = [];
var prop, queueUpdates = !dontQueueUpdates, propType, value, idx;
for(i=0; i<l; i++){
prop = keys[i];
value = object[prop];
propType = typeof(value);
if((idx = properties.indexOf(prop))===-1){
if(wrapProperty(object, prop)&&queueUpdates){
self.queueUpdate(object, prop, 'new', null, object[prop]);
}
}else{
if((object instanceof Array)&&(isNumeric(prop))){
if(values[idx] !== value){
if(queueUpdates){
self.queueUpdate(object, prop, 'updated', values[idx], value);
}
values[idx] = value;
}
}
oldKeys.splice(oldKeys.indexOf(prop), 1);
}
}
if(queueUpdates){
l = oldKeys.length;
for(i=0; i<l; i++){
idx = properties.indexOf(oldKeys[i]);
self.queueUpdate(object, oldKeys[i], 'deleted', values[idx]);
properties.splice(idx,1);
values.splice(idx,1);
};
}
};
self.addListener = function(callback){
var idx = _listeners.indexOf(callback);
if(idx===-1){
_listeners.push(callback);
}
};
self.removeListener = function(callback){
var idx = _listeners.indexOf(callback);
if(idx>-1){
_listeners.splice(idx, 1);
}
};
self.listeners = function(){
return _listeners;
};
self.queueUpdate = function(what, prop, type, was){
this.queueUpdates([{
type: type,
object: what,
name: prop,
oldValue: was
}]);
};
self.queueUpdates = function(updates){
var self = this, i = 0, l = updates.length||0, update;
for(i=0; i<l; i++){
update = updates[i];
_updates.push(update);
}
if(_updater){
clearTimeout(_updater);
}
_updater = setTimeout(function(){
_updater = false;
self.deliverChangeRecords();
}, 100);
};
self.deliverChangeRecords = function(){
var i = 0, l = _listeners.length, keepRunning = true;
for(i=0; i<l&&keepRunning; i++){
if(typeof(_listeners[i])==='function'){
if(_listeners[i]===console.log){
console.log(_updates);
}else{
keepRunning = !(_listeners[i](_updates));
}
}
}
_updates=[];
};
self._checkPropertyListing(true);
};
var _notifiers=[], _indexes=[];
extend.getNotifier = function(O){
var idx = _indexes.indexOf(O), notifier = idx>-1?_notifiers[idx]:false;
if(!notifier){
idx = _indexes.length;
_indexes[idx] = O;
notifier = _notifiers[idx] = new Notifier(O);
}
return notifier;
};
extend.observe = function(O, callback){
return new Observer(O, callback);
};
extend.unobserve = function(O, callback){
validateArguments(O, callback);
var idx = _indexes.indexOf(O),
notifier = idx>-1?_notifiers[idx]:false;
if (!notifier){
return;
}
notifier.removeListener(callback);
if (notifier.listeners().length === 0){
_indexes.splice(idx, 1);
_notifiers.splice(idx, 1);
}
};
})(Object, this);
}