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.
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*/ }
};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With