You cannot attach event listeners to individual variables.
The best way to do this is to place the variable in the object and force all users of the variable to access it through the “get” and “set” methods or more specifically named methods. When you set a value, you can check if the value is really changing, how you are interested and act accordingly. Here is an example:
var _isMenuReady = false; // do not access this directly function isMenuReady() { return(_isMenuReady); } function setMenuReady(val) { if (arguments.length < 1) { val = true; } if (!_isMenuReady && (val)) { _isMenuReady = val; // _isMenuReady has gone from false to true // do whatever you need to do now } _isMenuReady = val; } // sample code var ready = isMenuReady(); // returns whether the menu is ready or not setMenuReady(); // sets the menu to be ready now setMenuReady(false); // sets it back to not ready
You can even make it a private member of the object, so no one can get it directly outside the real access methods (although this is not necessary if all the code belongs to you and you collaborate without accessing the variable directly). But if you want to make it truly private, see this article for information on how to create private members. Essentially, you create a solid function closure, which local variables are only available inside the function. This is a cool technique.
function menuReadyTracker(initialValue) { var value = initialValue; var subscribers = []; this.get = function () { return(value); }; this.set = function(newVal) { if (newVal != value) { value = newVal; var o; for (var i = 0; i < subscribers.length; i++) { o = subscribers[i]; o.func.call(o.ctx, o.data); } } }
jsFiddle: http://jsfiddle.net/jfriend00/PYJef/
source share