侦听对Javascript对象值的更改

侦听对Javascript对象值的更改,javascript,jquery,Javascript,Jquery,是否可以(使用jQuery或其他方式)侦听非DOM Javascript对象(或变量)的值的更改?例如,我有: function MyObject() { this.myVar = 0; } var myObject = new MyObject(); myObject.myVar = 100; 当myVar的值发生变化并调用函数时,是否有办法监听?我知道我可以使用getter/setter,但它们在以前的IE版本中不受支持。如果IE很重要,我想你对它不感兴趣 但似乎有人写了一个垫片

是否可以(使用jQuery或其他方式)侦听非DOM Javascript对象(或变量)的值的更改?例如,我有:

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

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

myVar
的值发生变化并调用函数时,是否有办法监听?我知道我可以使用getter/setter,但它们在以前的IE版本中不受支持。

如果IE很重要,我想你对它不感兴趣

但似乎有人写了一个垫片,使这个问题重复


您基本上可以实现这种行为

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);

基本上你有两个选择

  • 使用非标准的
    watch
    方法,该方法仅在Firefox中可用
  • 使用旧IE版本不支持的getter和setter
第三个和跨平台的选择是使用轮询,这不是很好

查看
的示例

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*
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*
获取者和设置者的示例

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*
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*

有一个提议的对象可能是重复的。observe()这不适用于像setter那样设置值,对吗
o.myVar=100
不起作用,它必须是
o.setMyVar(100)
这正是我试图避免的-我希望它的功能像一个setter,尽管在所有浏览器中保持支持时,这看起来可能不可能。这可能是可用的最佳解决方案-它仍然排除IE7,但在一个有IE的世界中,没有什么是完美的……:)当你说“IE的旧版本”包括IE8吗?我知道它很旧,但它支持getter&setters吗?这个答案来自2011年。当时IE8还不算老。