如何监听动态添加的对象字段中的更改?

时间:2012-04-13 17:29:17

标签: javascript

我希望扩展Object和Array类,以便我能够在构建之后收听对其实例所做的任何更改。

我现在能做的最好的事情是为初始化/构建实例时给出的字段添加自定义get和set函数:

var myObj = new CustomObject({name:'foo'});

myObj.name = 'bar'; // this will log "'name' in 'myObj' updated:'bar'"

//however:

myObj.age = 85; // this mutation will slip by unnoticed, 
                // since the 'age' field was never specified 
                // at initialization meaning no custom set / get 
                // functions where attached.

有没有办法实现以下功能?

var myObj = new CustomObject();

myObj.name = 'foo';// this should log something like:
                   // "A new field 'name' was created for myObj with value 'foo'"

注意:我正在寻找一种不涉及民意调查的解决方案。

我现在拥有的(导致第一个代码块中显示的功能):

function CustomObject(data) {

    var that = this;

    for(var field in data){         
        prepField(field);                                   
    }

    function prepField(field){                  
        Object.defineProperty( that, field, {
            set: function(val){         
                data[field] = val;
                console.log(field,'in',that,'updated:',val);
            },
            get: function(){
                console.log(field,'in',that,'requested');
                return data[field];                 
            },
            enumerable:true
        });         
    }

    return this;

}

提前致谢!

1 个答案:

答案 0 :(得分:2)

Firefox(mozilla)有一个名为Proxy的东西可以做到这一点。

MDN Proxy docs

目前这是一个非标准功能,但似乎(或类似的东西)可能成为ECMAScript 6的一部分。

来自http://wiki.ecmascript.org/doku.php?id=harmony:proposals

enter image description here