在 JavaScript 中观察对象属性的变化 [英] Watch for object properties changes in JavaScript

查看:37
本文介绍了在 JavaScript 中观察对象属性的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Javascript Object.Watch 是否适用于所有浏览器?

我刚刚阅读了关于 watch() 方法的 Mozilla 文档

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

但是,我在 Safari 中找不到类似的东西.Internet Explorer 都没有.

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

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

How do you manage portability across browsers?

推荐答案

我创建了一个小的 object.watch shim 不久前.它适用于 IE8、Safari、Chrome、Firefox、Opera 等.

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

这篇关于在 JavaScript 中观察对象属性的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆