If you want to disable events when changing an object variable, you can configure a small Observer template for this object.
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'); });
Using instead of directly setting the property of an object, you use the setter method, which then triggers an event notification to other objects that view it.
JS FIDDLE
Richard Christensen
source share