Dies ist ein paar Jahre alt, aber es hat für mich super funktioniert. Ein SO-Benutzer hat vor einigen Jahren einen Open-Source-Object-Watcher gepostet. Sie ändert den Objektprototyp so, dass Sie nach Änderungen an bestimmten Eigenschaften des Objekts suchen.
window.watch('onclick', function() { console.log('changed'); });
window.onclick = function() { console.log('click1'); };
window.onclick = function() { console.log('click2'); };
JSFiddle: https://jsfiddle.net/gou48xpa/
Quellcode: https://gist.github.com/eligrey/384583 (mit dem MIT-Lizenz veröffentlicht)
if (!Object.prototype.watch) {
Object.defineProperty(Object.prototype, "watch", {
enumerable: false
, configurable: true
, writable: false
, value: function (prop, handler) {
var
oldval = this[prop]
, newval = oldval
, getter = function() {
return newval;
}
, setter = function (val) {
oldval = newval;
return newval = handler.call(this, prop, oldval, val);
}
;
if (delete this[prop]) { // can't watch constants
Object.defineProperty(this, prop, {
get: getter
, set: setter
, enumerable: true
, configurable: true
});
}
}
});
}
// object.unwatch
if (!Object.prototype.unwatch) {
Object.defineProperty(Object.prototype, "unwatch", {
enumerable: false
, configurable: true
, writable: false
, value: function (prop) {
var val = this[prop];
delete this[prop]; // remove accessors
this[prop] = val;
}
});
}
[yo Kumpel Ich habe gehört, Sie wie Ereignisse ... so habe ich einige Ereignisse, in Ihre Veranstaltungen ] (http://knowyourmeme.com/memes/xzibit-yo-dawg) :) – Liam