Skip to content

Instantly share code, notes, and snippets.

@zbabtkis
Last active December 31, 2015 07:29
Show Gist options
  • Save zbabtkis/7954625 to your computer and use it in GitHub Desktop.
Save zbabtkis/7954625 to your computer and use it in GitHub Desktop.
An Object.observe shim (use Object.observe = new ObjectObserver;)
ObjectObserver = function() {
var objects = []
, cache = []
, callbacks = [];
var compare = function(obj, old, change) {
var newObj = {};
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
if({}.toString.call(obj[i]) === "[object Object']") {
newObj[i] = clone(obj[i], old[i]);
} else if({}.toString.call(obj[i]) === '[object Function]') {
if(obj[i].toString() === old[i].toString()) {
change(obj[i]);
}
newObj[i] = obj[i].toString();
} else {
if(obj[i] !== old[i]) {
change(i, obj[i]);
};
newObj[i] = obj[i];
}
}
}
return newObj;
};
setInterval(function() {
for(var i = 0, j=objects.length; i < j; i++) {
cache[i] = compare(objects[i], cache[i], function(i) {
return function() {
for(var k = 0, l = callbacks[i].length; k < l; k++) {
callbacks[i][k].apply(objects[i],arguments);
}
}
}(i));
}
}, 0);
return function(obj, callback) {
var exists;
if(!callback) throw new Error("You must provide a callback");
for(var i = 0, j = objects.length; i < j; i++) {
if(obj ===objects[i]) {
exists = true;
callbacks[i].push(callback);
}
}
if(!exists) {
objects.push(obj);
cache.push(obj);
callbacks.push([callback]);
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment