how to add an eventListener to an Object in javascript which will fire when object is manipulated?
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.
KakambaWeb
Updated on July 26, 2022Comments
-
KakambaWeb almost 2 years
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 sayupdateLocalStorage()
which is working perfectly.My question is for this flow, can i create a custom event to my
ui_states
object something likeui_states.addEventListener('onchange', function(){ // do stuff })
to not to run thatupdateLocalStorage()
function every time when i manipulate the object?Thanks.
-
Pascal over 9 yearsI disagree. Events are absolutely not DOM only. But a concept to loosely couple components which can be implemented in "Dom-Less"-JS as well.
-
Jordan over 9 yearsYes, he is probably mixing these two concepts but yes, some pure javascript objects supports events like XMLHTTPRequest, RTCConnection, Worker, WebSocket... To complete my comment, no the Object object do not support events except (recently) with Object.observe (only for Chrome yet).
-
Deva over 9 yearsOkay, when I posted that answer, events were indeed only on DOM objects. Things have moved forward since then, obviously.