跟踪对象是否已更改 [英] Track whether object changed
本文介绍了跟踪对象是否已更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
// A simple Javascript Object / String
var object = "hello";
// Imagine a button in the DOM, and if it's clicked the object value will change
document.getElementById("button").onclick = function(){
window.object = "hello world";
}
// Now I would like to track and do something when the object is changed, ex:
object.onreadystatechange = function(){
alert(object);
}
注意:这听起来很愚蠢,因为我可以得到改变在按钮上的 onclick
事件中,但这不是我想要的,我想严格跟踪对象本身的变化以供任何使用,上面的代码是只是一个例子。
Note: This could sound stupid, because I could get the change in the onclick
event on the button, but this is not what I want, I want strictly to track the change on the object itself for any kind of use, the above code is is just an example.
推荐答案
你可以用get和set方法把它变成一个实际的对象:
Well you can make it an actual oject with get and set methods:
// A simple Javascript Object
var object = new (function(){
this.text = 'hello';
this.setText = function(msg){
this.text = msg
//on change event
}
})();
// Imagine a button in the DOM, and if it's clicked the object value will change
document.getElementById("button").onclick = function(){
object.setText('New Text');
}
这是一个演示小提琴: http://jsfiddle.net/maniator/BSYpz/
Here is a demo fiddle: http://jsfiddle.net/maniator/BSYpz/
这篇关于跟踪对象是否已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文