Reputation: 4040
how to find whether a value of variable is changed or not in javascript .
Upvotes: 6
Views: 54018
Reputation: 6109
var _variable;
get variable() {
return _variable;
}
set variable(value) {
_variable = value;
// variable changed
}
or if you don't need the value of the variable later:
set variable(value) {
// variable changed
}
Upvotes: 3
Reputation: 42140
There is a way to watch variables for changes: Object::watch
- some code below
/*
For global scope
*/
// won't work if you use the 'var' keyword
x = 10;
window.watch( "x", function( id, oldVal, newVal ){
alert( id+' changed from '+oldVal+' to '+newVal );
// you must return the new value or else the assignment will not work
// you can change the value of newVal if you like
return newVal;
});
x = 20; //alerts: x changed from 10 to 20
/*
For a local scope (better as always)
*/
var myObj = {}
//you can watch properties that don't exist yet
myObj.watch( 'p', function( id, oldVal, newVal ) {
alert( 'the property myObj::'+id+' changed from '+oldVal+' to '+newVal );
});
myObj.p = 'hello'; //alerts: the property myObj::p changed from undefined to hello
myObj.p = 'world'; //alerts: the property myObj::p changed from hello to world
// stop watching
myObj.unwatch('p');
Upvotes: 6
Reputation: 522125
By comparing it to a known state to see if it differs. If you're looking for something like variable.hasChanged
, I'm pretty sure that doesn't exist.
Upvotes: 0
Reputation: 26132
Ehm?
var testVariable = 10;
var oldVar = testVariable;
...
if (oldVar != testVariable)
alert("testVariable has changed!");
And no, there is no magical "var.hasChanged()" nor "var.modifyDate()" in Javascript unless you code it yourself.
Upvotes: 16
Reputation: 9083
If you are a firefox user you can check using firebug. If you are using IE we can put alert statements and check the values of the variables.
Upvotes: 1