javascript - 监听 Javascript 对象值的变化

标签 javascript jquery

是否有可能(使用 jQuery 或其他方式)监听非 DOM Javascript 对象(或变量)值的变化?因此,例如,我有:

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

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

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

最佳答案

基本上你有两个选择

  • 使用仅在 Firefox 中可用的非标准 watch 方法
  • 使用旧版 IE 不支持的 getter 和 setter

第三种也是跨平台的选择是使用不太好的轮询

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*

getterssetters 的示例

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*

关于javascript - 监听 Javascript 对象值的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6689931/

相关文章:

javascript - 无法从纽约时报 API 检索数据

javascript - JS : "this" in function context in strict mode, MDN 规范与 chrome 67 实现不匹配

javascript - Jquery,无法删除克隆的元素

javascript - 计算父 div 内的所有数字,然后按总计对它们进行排序

javascript - jQuery : how to hide div after animation?

javascript - 提交时从给定的复选框中至少强制选择一个复选框

javascript - 如何使用foreach循环在mysql表中插入一个静态值和多个动态值?

javascript - 如何添加自动编号表行?

javascript - Phonegap 入门

jquery - 为什么这个 div 在 Chrome 中加载不一致?错误?