Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track whether object changed

// A simple Javascript Object / String
var object = "hello";

// Imagine a button in the DOM, and if it's clicked the object value will change
document.getElementById("button").onclick = function(){
   window.object = "hello world";
}

// Now I would like to track and do something when the object is changed, ex:
object.onreadystatechange = function(){
   alert(object);
}

Note: This could sound stupid, because I could get the change in the onclick event on the button, but this is not what I want, I want strictly to track the change on the object itself for any kind of use, the above code is is just an example.

like image 791
Adam Halasz Avatar asked May 10 '11 15:05

Adam Halasz


1 Answers

Javascript does not allow you to set programmatic watchpoints/events on arbitrary objects/variables.

You can use encapsulation to hide individual values inside the object from the outside world, allowing them to be modified only through dedicated "setter" functions that have the side-effects you desire.

like image 153
Lightness Races in Orbit Avatar answered Sep 17 '22 19:09

Lightness Races in Orbit