JavaScript中监测对象属性的变化

38

1
复制链接:https://dev59.com/53NA5IYBdhLWcg3wQ7i4 - Crescent Fresh
这里有一个相关的讨论: https://dev59.com/53NA5IYBdhLWcg3wQ7i4 - Mehmet Duran
3个回答

68

我之前创建了一个小的object.watch替代方案。它能够在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;
    };

5
它仍然在 Github 上,但我将其移动到 gist (https://gist.github.com/384583),因为我认为它不够重要以至于需要一个存储库。 - Eli Grey
3
它在非DOM对象上对IE8是否真正有效? - Greg
在某些DOM属性(例如el.style.width)上,这在Safari中无法正常工作。 - Jani Hartikainen
使用watch后,我无法遍历属性。也许最好删除带有“delete this[prop]”的行? - Ivan P.
我认为这段代码对于POCO对象应该很好用。对于DOM元素,你应该考虑使用attrchange库(https://github.com/meetselva/attrchange)。 - user94893
显示剩余7条评论

2

很遗憾,这不是一种便携式的解决方案。据我所知,IE没有类似的功能,但如果有的话会非常棒。


-4

你可能可以通过覆盖方法和变量来实现自己的通知系统。但我认为这并不是非常关键的问题,而且我也不知道你打算用这样的系统做什么。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接