监视JavaScript中的对象属性更改

时间:2009-08-13 01:49:34

标签: javascript object cross-browser properties watch

  

可能重复:
  Javascript Object.Watch for all browsers?

我刚刚阅读了Mozilla的watch() method文档。它看起来非常有用。

但是,我找不到类似于Safari的东西。不是Internet Explorer。

如何管理跨浏览器的可移植性?

3 个答案:

答案 0 :(得分:66)

我刚才为此创建了一个小object.watch shim。它适用于IE8,Safari,Chrome,Firefox,Opera等。

/*
* 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;
    };

答案 1 :(得分:1)

不幸的是,这不是一个便携式解决方案。根据我的知识,IE没有这样的东西,但如果有

那就太棒了

答案 2 :(得分:-4)

您可以通过覆盖方法和变量来实现自己的通知系统。我不认为它是那么重要,但我不知道你打算用这样一个系统做什么。