Skip to content Skip to sidebar Skip to footer

Watch Variable Changes In Jquery/Javascript

Is there a way to watch variable changes in Jquery/Javascript like it is the case in AngularJS ?

Solution 1:

Angular uses a digest cycle to detect changes after you update a variable. For instance, when you click on an element, it will change variables in scopes, and will immediately trigger a look through to see what has changed. You can accomplish something similar using a simple interval function:

var _watch = null;
var test = null;
setInterval(function() {
    if ( _watch !== test ) {
        _watch = test;
        console.log('Variable changed.', test);
    }
}, 100);

To test this out, simply type test = "test" in the console, and you should see "Variable changed."


Solution 2:


Solution 3:

Use a getter/setter method:

var log = ['test'];
var obj = {
  get latest () {
    if (log.length == 0) return undefined;
    console.log('getting latest!'); // or trigger an event
    return log[log.length - 1]
  }
}
console.log (obj.latest); // Will return "test".

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/get


Post a Comment for "Watch Variable Changes In Jquery/Javascript"