Is it possible to listen for changes to an object's attributes in JavaScript?

后端 未结 7 1695
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 23:37

I\'m working on a fiddly web interface which is mostly built with JavaScript. Its basically one (very) large form with many sections. Each section is built based on options

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 00:16

    Thanks for the comments guys. I've gone with the following:

    var EntriesRegistry = (function(){
    
        var instance = null;
    
        function __constructor() {
    
            var
                self = this,
                observations = {};
    
            this.set = function(n,v)
            {
                self[n] = v;
    
                if( observations[n] )
                    for( var i=0; i < observations[n].length; i++ )
                        observations[n][i].apply(null, [v, n]);
    
            }
    
            this.get = function(n)
            {
                return self[n];
            }
    
            this.observe = function(n,f)
            {
    
                if(observations[n] == undefined)
                    observations[n] = [];
    
                observations[n].push(f);
            }
    
        }
    
        return new function(){
            this.getInstance = function(){
                if (instance == null)
                {
                    instance = new __constructor();
                    instance.constructor = null;
                }
                return instance;
            }
        }
    })();
    
    var entries = EntriesRegistry.getInstance();
    
    var test = function(v){ alert(v); };
    
    entries.set('bob', 'meh');
    
    entries.get('bob');
    
    entries.observe('seth', test);
    
    entries.set('seth', 'dave');
    

    Taking on-board your comments, I'll be using event delegation on the form objects to update the registry and trigger the registered observing methods.

    This is working well for me so far... can you guys see any problems with this?

提交回复
热议问题