How to add eventListener to an object in javascript that will fire when the object is manipulated?

I have a complex user interface structure that is dynamically controlled and says that I have a ui_state object where I save the user’s last state of the user interface, such as the tab was visible, what is inside this tab, etc.

For example:

 var ui_states = { tabs : [ { name : "some tab", active : true, children : { ... } }, { name : "some other tab", children : { ... } } ] } 

I save this to html5 localStorage , and when the user refreshes the site, he opens the page again. And every time the user interface changes this object, it changes accordingly. And right after changing it, I need to run let say updateLocalStorage() , which works fine.

My question is for this thread, can I create my own event for my ui_states object, something like ui_states.addEventListener('onchange', function(){ // do stuff }) so as not to run this updateLocalStorage() function every time when do i manipulate an object?

Thank.

+7
javascript javascript-events event-handling events
Oct 11 '10 at 2:43
source share
2 answers

You mix JavaScript programming with DOM programming. Events are purely a DOM concept. JS objects do not support event handlers.

The only way to do this is to create getters and setters. There are ways to do this using special properties , but, unfortunately, browser support may be a bit. Another way to do this is to use explicit methods and private variables. It is possible, but a little complicated.

+3
Oct 11 '10 at 2:58
source share

The bob.js framework (written by me) supports events for objects with pure JavaScript. You can either create an object representation of the event that supports registering / unregistering the handler, or you can tell bob.js about the creation of functions on your object. Here's the second approach (as the example is cleaner to read):

 var DataListener = function() { var fire = bob.event.namedEvent(this, 'received'); this.start = function(count) { for (var i = 0; i < count; i++) { fire(i + 1); } }; }; var listener = new DataListener(); listener.add_received(function(data) { console.log('data received: ' + data); }); listener.start(5); // Output: // data received: 1 // data received: 2 // data received: 3 // data received: 4 // data received: 5 
+2
Apr 6 '13 at 11:53 on
source share



All Articles