开发者

Listen for change to Javascript object value

开发者 https://www.devze.com 2023-03-20 00:59 出处:网络
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开发者_如何学JAVA, I have:

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开发者_如何学JAVA, 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.


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*


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


You can basically implement such behavior

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

    this.setMyVar = function (val) {
       this.MyVar = val;

       if (onMyVarChangedCallback) {
           onMyVarChangedCallback();
       }
    }
}

function onChangeListener() {
   alert('changed');
}

var o = new MyObject(onChangeListener);
0

精彩评论

暂无评论...
验证码 换一张
取 消