Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add an eventListener to an Object in javascript which will fire when object is manipulated?

I have a complicated UI structure which is manipulated dynamically, and say I have an ui_state object where i keep user's latest UI states such as which tab was visible, what was inside that tab etc.

For instance:

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

I keep this on html5 localStorage and when user refreshes the site it reopens the page the same. And everytime when the UI changes this object is changed accordingly. And just after changing it i need to run let's say updateLocalStorage() which is working perfectly.

My question is for this flow, can i create a custom event to my ui_states object something like ui_states.addEventListener('onchange', function(){ // do stuff }) to not to run that updateLocalStorage() function every time when i manipulate the object?

Thanks.

like image 644
KakambaWeb Avatar asked Oct 11 '10 02:10

KakambaWeb


People also ask

Can you add an event listener to an object?

You can add event listeners to any DOM object not only HTML elements. i.e the window object. The addEventListener() method makes it easier to control how the event reacts to bubbling.

What is the event name that fires when a user clicks on an object?

When a user clicks a button or presses a key, an event is fired. These are called a click event or a keypress event, respectively.

How can we add an element to an object in JavaScript?

Using square [] bracket: In JavaScript, we can use [] brackets to add elements to an object.


1 Answers

You're mixing up JavaScript programming with DOM programming. Events are purely a DOM concept. JS objects do not support event handlers.

The only way to do it is to create getters and setters. There are ways to do this with special properties, but unfortunately, browser support is a bit maybe. The other way to do it is using explicit methods and private variables. This is possible but a little complex.

like image 159
staticsan Avatar answered Nov 15 '22 20:11

staticsan