Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen for change to Javascript object value

Tags:

javascript

Is it possible (using jQuery or otherwise) to listen for a change in the value of a non-DOM Javascript object (or variable)?

So, for instance, I have:

function MyObject(){
    this.myVar = 0;
}

var myObject = new MyObject();
myObject.myVar = 100;

Is there a way to listen for when the value of myVar changes and call a function?

I know that I could use getter/setters, but they aren't supported in previous versions of IE.

like image 867
redhotvengeance Avatar asked Feb 08 '26 02:02

redhotvengeance


2 Answers

Basically you have two options

  • use non-standard watch method which is available only in Firefox
  • use getters and setters which are not supported in older IE versions

The third and cross-platform option is to use polling which is not so great

Example of watch

var myObject = new MyObject();

// Works only in Firefox
// Define *watch* for the property
myObject.watch("myVar", function(id, oldval, newval){
    alert("New value: "+newval);
});

myObject.myVar = 100; // should call the alert from *watch*

Example of getters and setters

function MyObject(){
    // use cache variable for the actual value
    this._myVar = undefined;
}

// define setter and getter methods for the property name
Object.defineProperty(MyObject.prototype, "myVar",{
    set: function(val){
        // save the value to the cache variable
        this._myVar = val;
        // run_listener_function_here()
        alert("New value: " + val);
    },
    get: function(){
        // return value from the cache variable
        return this._myVar;
    }
});

var m = new MyObject();
m.myVar = 123; // should call the alert from *setter*
like image 126
Andris Avatar answered Feb 09 '26 16:02

Andris


If IE is important, I guess you are not interested in Watch

But someone seems to have written a shim which makes this question a duplicate

Watch for object properties changes in JavaScript

like image 23
mplungjan Avatar answered Feb 09 '26 14:02

mplungjan