Watch for object properties changes in JavaScript [duplicate]

懵懂的女人 提交于 2019-11-26 04:07:27

问题


Possible Duplicate:
Javascript Object.Watch for all browsers?

I just read Mozilla\'s documentation for the watch() method. It looks very useful.

However, I can\'t find something similar for Safari. Neither Internet Explorer.

How do you manage portability across browsers?


回答1:


I have created a small object.watch shim for this a while ago. It works in IE8, Safari, Chrome, Firefox, Opera, etc.

/*
* object.watch v0.0.1: Cross-browser object.watch
*
* By Elijah Grey, http://eligrey.com
*
* A shim that partially implements object.watch and object.unwatch
* in browsers that have accessor support.
*
* Public Domain.
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/

// object.watch
if (!Object.prototype.watch)
    Object.prototype.watch = 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
            if (Object.defineProperty) // ECMAScript 5
                Object.defineProperty(this, prop, {
                    get: getter,
                    set: setter
                });
            else if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { // legacy
                Object.prototype.__defineGetter__.call(this, prop, getter);
                Object.prototype.__defineSetter__.call(this, prop, setter);
            }
        }
    };

// object.unwatch
if (!Object.prototype.unwatch)
    Object.prototype.unwatch = function (prop) {
        var val = this[prop];
        delete this[prop]; // remove accessors
        this[prop] = val;
    };



回答2:


Unfortunately, this is not a portable solution. IE has nothing like this to my knowledge, though it would be awesome if there was




回答3:


You could probably implement your own system of notifcation, by overwriting methods and variables. I don't see it as being that critical though, but I don't know what you planning on doing with such a system.



来源:https://stackoverflow.com/questions/1269633/watch-for-object-properties-changes-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!