Is it possible to track a variable change in javascript? I would like to be able to launch a function when a variable has been changed in a class.
<script>
var mywindow = new Box();
mywindow.title = "newtitle";
//Launches mywindow.applyTitle() and changes html
</script>
You could probably use an explicit method for setting the value and attach your callbacks to that. Something along this would work:
var Box = new Class({
setTitle: function(title) {
this.title = title;
// call your callbacks now. you probably need some way to register them btw
}
});
Adapt the idea to fit your class syntax...
There is also a not so well supported getter/setter syntax for JS (equivalent to properties in Python). See http://ejohn.org/blog/javascript-getters-and-setters/ .
Not automatically. Probably best would be to add to the prototype of the Box
class with a setter function that you can use instead of setting the property directly.
Example: http://jsfiddle.net/PEYyk/
var Box = function() {
// the constructor
};
Box.prototype.setTitle = function( new_title ) {
this.title = new_title;
this.applyTitle();
};
Box.prototype.applyTitle = function() {
// apply the title
};
Then call it like this:
var mywindow = new Box();
mywindow.setTitle( "newtitle" );