1

I was wondering wether there is a way to attach eventlisteners to variables. The idea is to do something like this:

someVar.addEventListener('change', someTodo, false);

So once someVar is changed by i.e. someVar=1, someTodo would be executed.

I think to understand that - in theory - eventlisteners can be added to everything in the DOM, the problem beeing that variables do not trigger those events, while HTML objects DO trigger them. If that is indeed correct, the extended question would be: How to train DOM objects to trigger events? I have read something about prototyping, is that the trick here?

Please note: I like to understand and write all of my code myself. So I'd rather be interested in the theory then using some existing thing like jQuery, where all sorts of miracles are baked right in.

Marco

Marco P.
  • 153
  • 6
  • duplicate: http://stackoverflow.com/questions/1029241/javascript-object-watch-for-all-browsers – kirilloid Feb 14 '11 at 06:23
  • 1
    This question has been answered here: [StackOverflow - 4989337](http://stackoverflow.com/questions/1759987/detect-variable-change-in-javascript) – Ryan Feb 14 '11 at 06:25

1 Answers1

0

The safe and time tested approach is to use getters and setters on your objects (ie, you only allow access to the variable through object methods like getX()/setX()). You could then have overload setX() to trigger callbacks. There are some languages like Lua and Python where access to an object's members can be caught with meta functions but I do not believe Javascript supports this in any way.

SpliFF
  • 35,724
  • 15
  • 80
  • 113