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?

Tim
  • 5,893
  • 3
  • 35
  • 64

3 Answers3

2

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
  • 5,145
  • 34
  • 37
  • 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 Sep 29 '10 at 08:59
  • Yeah, this was just to show some code - modify it to whatever framework you use :-) – AHM Sep 29 '10 at 09:01
  • 1
    @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 Gallarde Sep 29 '10 at 09:22
  • @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 Sep 29 '10 at 09:26
  • @AHM, @Tim - [here's one good explanation](http://stackoverflow.com/questions/1592384/adding-prototype-to-object-literal/1592398#1592398). – Reigel Gallarde Sep 29 '10 at 09:27
0

try this:

var book = {
    _year: 2004,
    edition: 1
};
Object.defineProperty(book, "year", {
    get: function(){
        return this._year;
    },
    set: function(newValue){
        if (newValue > 2004) {
            this._year = newValue;
            this.edition += newValue - 2004;
        }
    }
});
book.year = 2005;
alert(book.edition); 

I use this method wrote a bidirectional model view binding jquery plugin jQueryMV https://github.com/gonnavis/jQueryMV .

gonnavis
  • 336
  • 1
  • 7
  • 16
0

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
  • 2,780
  • 23
  • 26