3

我正在尝试在 javascript 中创建一个对象观察者。

这是据我所知:

//object to observe an object
        observe : {
            parent : this, //keep context of parent
            references : {}, //keep track of setted references
            originals : {}, // also for the originals
            callStack : 0, // trying to prevent the callstack

            // set an object to observe..
            setObject : function ( name, object ){
                this.references[name] = object;
                //app.utils.extendObject is a working object extending function.
                this.originals[name] = app.utils.extendObject( new Object , object );
                //start watching the object
                this.watchObject( name );
            },

            watchObject : function ( referenceName ){
                this.callStack++;
                //walk through reference
                for( prop in this.references[referenceName] ){
                    // if the reference differs from the original...
                    if( this.references[referenceName][prop] !== this.originals[referenceName][prop]  ){
                        //... log the differance
                        console.log( referenceName + " with property " + prop + " has changed." );
                    }
                }
                // set variable with call to this function
                var func = eval( "app.utils.observe.watchObject(" + referenceName + ")" );

                //read somewhere this could do the trick
                if( callStack == 1000 ){
                    setTimeout( func , 100 );
                }
                func();

            }

        }

问题是调用堆栈错误,有没有更好的方法来观察这个?当然,我目前可以在 Chrome 中使用 Object.observe,但我想要一个跨浏览器的解决方案。

任何帮助表示赞赏!

4

1 回答 1

1

我稍微修改了您的代码,callback为方法添加了功能watchObject。如果您想监听更改并执行一些操作,这很有用。

watchObject: function (referenceName, callback) {
    for (prop in this.references[referenceName]) {
        if (this.references[referenceName][prop] !== this.originals[referenceName][prop]) {
            console.log(referenceName + " with property " + prop + " has changed.");
            callback && callback.call(this.references[referenceName], this.originals[referenceName][prop], this.references[referenceName][prop]);
            this.originals[referenceName][prop] = this.references[referenceName][prop];
        }
    }
}

另外我setInterval放在setObject

var self = this;
setInterval(function() {
    self.watchObject(name, callback);
}, 300);

http://jsfiddle.net/59Fnt/1/

于 2013-03-28T21:00:00.820 回答