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:
You can use obj.watch
but it's only supported in Gecko (Basically firefox) for now.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch
Edit: For Chrome , Object.observe
can be used.
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
returnlog[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"