1

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...)

Tapefreak
  • 982
  • 1
  • 13
  • 16
  • 2
    I think what you ought to do is replace your variable with an object, and design that object with a setter method that runs whatever code you want at the same time its properties are changed. – Blazemonger Oct 12 '11 at 14:27
  • Not very sure, but you can try http://documentcloud.github.com/backbone/ – Riz Oct 12 '11 at 14:29
  • can you post a piece of code please ? – joe Oct 12 '11 at 14:26
  • Yes I'm aware that I could include a setter, though that would require rewriting a good amount of code. I was wondering if there is anything built-in to Javascript or jQuery that facilitates this. From what I've seen so far I am thinking the answer to that is "No." I am planning on implementing Backbone in the next iteration of my project actually - I will probably just let Backbone take care of it for me. Thanks for all the helpful answers and suggestions thus far! – Tapefreak Oct 12 '11 at 15:04

4 Answers4

2

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
pimvdb
  • 151,816
  • 78
  • 307
  • 352
1

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.

Community
  • 1
  • 1
John Strickler
  • 25,151
  • 4
  • 52
  • 68
1

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.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
0

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:

etuardu
  • 5,066
  • 3
  • 46
  • 58