1

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>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
nebkat
  • 8,445
  • 9
  • 41
  • 60

2 Answers2

2

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/ .

Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105
2

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" );
user113716
  • 318,772
  • 63
  • 451
  • 440