开发者

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

开发者 https://www.devze.com 2023-04-12 18:01 出处:网络
开发者_JS百科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 liste

开发者_JS百科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...)


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


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.


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.


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:

  • defining getters and setters
  • defining a new property
0

精彩评论

暂无评论...
验证码 换一张
取 消