0

I have a global variable that is only set to true when the user enters certain inputs, and I want to be able to have a function fire off. Some of these inputs are not via the handlers, so I can't use the JQuery change() function.

Any advice on how to workaround this problem?

Louis93
  • 3,609
  • 8
  • 43
  • 86
  • More context is necessary here. What do have so far? What did you try? Why didn't what you tried work? – Alex Wayne May 30 '13 at 01:17
  • There is no event to check if a variable changes, other than using an interval and repeatedly checking the variable, or doing what most people do, fire the function instead of changing the variable when the inputs change. – adeneo May 30 '13 at 01:19

2 Answers2

3

use a custom getter to do something else when the value changes:

myGlobal=true;


(function(){
  var shadow=myGlobal;
Object.defineProperty(
   window, 
   "myGlobal", 
   {
     get: function() {return shadow;}, 
     set: function(v){alert( 'myGlobal is now ' + v); return shadow=v;}
   }
);

}());

myGlobal=false;
myGlobal=true;

this works in old-ish IE and imposes less of a perf hit than Object.watch() and polyfills.

dandavis
  • 14,821
  • 4
  • 34
  • 35
0

You can use the non-standard object.watch. Here is an implementation: https://gist.github.com/eligrey/384583

See Listening for variable changes in JavaScript or jQuery

Community
  • 1
  • 1
Fallexe
  • 596
  • 2
  • 11