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

后端 未结 7 1707
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  孤街浪徒
    2020-12-03 00:06

    Small modification to the previous answer : by moving the observable code to an object, one can make an abstraction out of it and use it to extend other objects with jQuery's extend method.

    ObservableProperties = {
        events : {},
        on : function(type, f)
        {
            if(!this.events[type]) this.events[type] = [];
            this.events[type].push({
                action: f,
                type: type,
                target: this
            });
        },
        trigger : function(type)
        {
            if (this.events[type]!==undefined)
            {
                for(var e = 0, imax = this.events[type].length ; e < imax ; ++e)
                {
                    this.events[type][e].action(this.events[type][e]);
                }
            }
        },
        removeEventListener : function(type, f)
        {
            if(this.events[type])
            {
                for(var e = 0, imax = this.events[type].length ; e < imax ; ++e)
                {
                    if(this.events[type][e].action == f)
                        this.events[type].splice(e, 1);
                }
            }
        }
    };
    Object.freeze(ObservableProperties);
    
    var SomeBusinessObject = function (){
        self = $.extend(true,{},ObservableProperties);
        self.someAttr = 1000
        self.someMethod = function(){
            // some code
        }
        return self;
    }
    

    See the fiddle : https://jsfiddle.net/v2mcwpw7/3/

提交回复
热议问题