Javascript eventener for changes to an object variable

I have an object variable that has several properties.

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

How to write an event listener that listens for changes to any of the properties.

Thanks for your suggestions.

+7
source share
3 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*/ } }; 
+12
source

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

+5
source

I know this is an old question, but if you do this for debugging suggestions, you can add a listener using your debugging tool at your browser just like you are debugging a script.

Personally, I use Firebug in Firefox, after opening, go to the DOM tab, find your variable, then ( similar to adding breakpoints to the script ) add breakpoints . It will break and scroll to a specific line of code that will handle the change in the variable.

Mark it -> Firefox FIREBUG or Google Chrome DEVELOPER TOOL

0
source

All Articles