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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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.
Yeah, this was just to show some code - modify it to whatever framework you use :-)
@Tim - No, this is not Prototype framework, it's just Vanilla Javascript, no framework detected. Here's a link.
@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.
0

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

Comments

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.