Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript event listener for changes in an object variable [duplicate]

I have an object variable that has several properties.

MyVar = {"prop1" : 0, "prop2": 0....};

How do I write an event listener that listens for a change in any of the properties.

Thanks for your suggestions.

like image 900
frenchie Avatar asked May 02 '11 17:05

frenchie


2 Answers

With ES5 you have setters:

var MyVar = {
  _prop1: 0,
  get prop1() { return this._prop1; },
  set prop1(value) { this._prop1 = value; /*Listener code can go here*/ }
};
like image 141
davin Avatar answered Oct 05 '22 20:10

davin


If you want to fire off events when an objects variable changes, you could set up a small Observer pattern for that obj.

var MyVar = {
    prop1: "Foo",
    prop2: "Bar",
    events: {},

    setProp1: function(prop1) {
        this.prop1 = prop1;
        this.notify('prop1', this.prop1);
    },

    setProp2: function(prop2) {
        this.prop2 = prop2;
        this.notify('prop2', this.prop1);
    },

    addEvent: function(name) {
        if (typeof this.events[name] === "undefined") {
            this.events[name] = [];
        }
    },

    register: function(event, subscriber) {
        if (typeof subscriber === "object" && typeof subscriber.notify === 'function') {
            this.addEvent(event);
            this.events[event].push(subscriber);
        }
    },

    notify: function(event, data) {
        var events = this.events[event];
        for (var e in events) {
            events[e].notify(data);
        }
    }
};

var Prop1 = {
    notify: function() {
        alert('prop1 changed');
    }
};

var Prop2 = {
    notify: function() {
        alert('prop2 changed');
    }
};

$(document).ready(function(){
    MyVar.register('prop1',Prop1);
    MyVar.register('prop2',Prop2);

    MyVar.setProp1('New Var');
    MyVar.setProp2('New Var');
});

Usage instead of setting the object property directly you use a setter method which then fires off a notify event to other objects that are watching it.

JS FIDDLE

like image 36
Richard Christensen Avatar answered Oct 05 '22 18:10

Richard Christensen