views:

36

answers:

2

I declare a variable which gets it's value through another event out of a select-box. Since there are different events which change the variable (lets name it z), I want to get informed when the variable gets changed.

So my question is: What is the best way to get informed when a variable gets changed? z.change(function(){}); throws an error.

Are there ways to do this without a hidden input-field or other helpers like that?

+2  A: 

It's not really possible, but some browsers support getters and setters, and with them you could implement something that called an external function when the value is chanced. If you want this to work in all browsers, then you could go the old fashioned way of doing this:

var Item = function (val) {
    this._val = val;
}

Item.Prototype.setValue = function (val) { 
    this._val = val;
    // call external function here!
}
Item.Prototype.getValue = function () {
    return this._val;
}

And then always remember to only access the property through these functions.

AHM
Thank you, looks very good, but this is the Prototype-way of doing it, right? Because I'm using jQuery. I will try a rewrite.
Tim
Yeah, this was just to show some code - modify it to whatever framework you use :-)
AHM
@Tim - No, this is not `Prototype` framework, it's just Vanilla Javascript, no framework detected. [Here's a link](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/prototype).
Reigel
@Riegel - yeah, that's right. It's all because of the Prototype frameworks irritating name - my example was prototypal inheritance, the kind javascript provides by itself, without a framework.
AHM
@AHM, @Tim - [here's one good explanation](http://stackoverflow.com/questions/1592384/adding-prototype-to-object-literal/1592398#1592398).
Reigel
Thanks your your explanations, this is working fine!
Tim
A: 

You should be interested in http://plugins.jquery.com/project/watch which is not as complete as SpiderMonkey's method, but actually works.

Pier Paolo Ramon