Mathemagician Mathemagician - 1 month ago 17
AngularJS Question

Watch variable changes in Jquery/Javascript

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

Answer

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."

Comments