Tapefreak
Tapefreak

Reputation: 982

Is there any way in JS to 'bind' a function to a variable's state?

Similar to binding an event, but rather to the changing of a variable. Is the only way to facilitate this by creating a set() function for each variable, or is it possible to bind a listener to the variable?

I find myself writing if statements around variables throughout several functions, to check their state. I would like to have a function fire whenever that variable changes.

(or is this a Bad Idea...)

Upvotes: 1

Views: 397

Answers (4)

etuardu
etuardu

Reputation: 5536

I suspect what you want can't be done with variables. Instead, you can do it with object members through getters/setters or properties. These concepts are quite commons in Object Oriented Programming. Here are some pointers:

Upvotes: 0

Aadit M Shah
Aadit M Shah

Reputation: 74234

It's possible and also a viable option in many circumstances. As @John pointed out, you can watch and unwatch the properties of objects in JavaScript. However, this only works in Firefox. Instead, I suggest you use getters and setters to achieve the result you want as @pimvdb pointed out. Note however that both these alternatives only work on the properties of objects (and global variables if you treat them as properties). You cannot achieve the same result on local variables.

Upvotes: 1

pimvdb
pimvdb

Reputation: 154918

You could make use of setters like this: http://jsfiddle.net/DeyCP/1/.

var obj = (function(func) {
    var variable;

    return {
        get something() {
            return variable;
        },

        set something(value) {
            variable = value;
            func();
        }
    };
})(function() {
    alert(123);
});

Then,

obj.something = 'foo'; // alerts 123
obj.something;         // returns foo

Upvotes: 2

John Strickler
John Strickler

Reputation: 25421

You can use the watch function from the Object.prototype.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch

See this answer for more info.

Upvotes: 1

Related Questions