Javascript: how to constantly control the value of variables

How can I constantly check the value of variables. For example:

if(variable == 'value'){ dosomething(); } 

This will work if I loop it all the time or something like that, but is there an effective way to start as soon as the variable is set to this value?

+7
source share
5 answers

Object.watch :

The clock for the property to which the value is to be assigned, and runs the function when this happens.

Object.watch () for all browsers? talks about cross-browser ways to make Object.watch in browsers that don't support it natively.

+10
source
 Object.defineProperty(Object.prototype, 'watch', { value: function(prop, handler){ var setter = function(val){ return val = handler.call(this, val); }; Object.defineProperty(this, prop, { set: setter }); } }); 

How to use:

 var obj = {}; obj.watch('prop', function(value){ console.log('wow!',value); }); obj.prop = 3; 
+6
source

As @Pekka commented, you can constantly poll the variable from the timer. The best solution, if all this is your code that modifies a variable, is not only to simply set the variable directly, but rather so that all setters call the function. The function can then set the variable and perform any additional processing.

 function setValue(value) { myVariable = value; notifyWatchers(); } 
+4
source

If you encapsulate your variable so that the value can only be set by calling the function, this gives you the opportunity to check the value.

 function ValueWatcher(value) { this.onBeforeSet = function(){} this.onAfterSet = function(){} this.setValue = function(newVal) { this.onBeforeSet(value, newVal) value = newVal; this.onAfterSet(newVal) } this.getValue = function() { return value; } } var name = new ValueWatcher("chris"); wacthedName.onBeforeChange = function(currentVal, newVal) { alert("about to change from" + currentVal + " to " + newVal); } name.setValue("Connor"); 
+4
source

Use setInterval:

 var key = '' setInterval(function(){ if(key == 'value'){ dosomething(); } }, 1000); 
+3
source

All Articles