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,438
  • 68
  • 55
  • 126
nebkat
  • 8,236
  • 9
  • 39
  • 59

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
  • 25,789
  • 12
  • 75
  • 102
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
  • 310,407
  • 61
  • 442
  • 435