2011-07-14 40 views
9

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

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

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

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

+0

可能重复的[JavaScript的 - 手表给对象特性的变化(http://stackoverflow.com/questions/1269633/javascript-watch-for-object-properties - 改变) – mplungjan

回答

4

如果IE是很重要的,我想你不感兴趣的Watch

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

Watch for object properties changes in JavaScript

+0

这可能是最好的解决方案 - 它仍然排除IE7,但在与IE浏览器的世界,没有什么可以是完美的:) :) – redhotvengeance

+0

https://github.com/melanke/Watch.JS我认为是最好的方式来使用手表 – django

+0

Downvoting没有评论不帮助任何人 – mplungjan

1

基本上可以实现这样的行为

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

这不会像设置一个设置值的工作,虽然,对吧? 'o.myVar = 100'不会工作,它必须是'o.setMyVar(100)'这就是我想要避免的 - 我想让它的功能像一个setter,虽然它看起来像这在所有浏览器中保持支持时可能无法实现。 – redhotvengeance

+0

ohhh ..我现在看到问题更近.. –

9

基本上你有两个选择

  • 使用非标准watch方法仅在Firefox可以未在旧的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* 

getters实施例和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* 
+0

当你说“旧版本的IE”,这包括IE8?我知道这是旧的,但它支持getter&setters? – evolutionxbox

+0

这个答案是从2011年开始的。当时IE8还没那么老。 – Andris