用于对象变量更改的 javascript 事件侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5860218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript event listener for changes in an object variable
提问by frenchie
I have an object variable that has several properties.
我有一个具有多个属性的对象变量。
MyVar = {"prop1" : 0, "prop2": 0....};
How do I write an event listener that listens for a change in any of the properties.
如何编写侦听任何属性更改的事件侦听器。
Thanks for your suggestions.
感谢您的建议。
回答by davin
With ES5 you have setters:
使用 ES5,你有 setter:
var MyVar = {
_prop1: 0,
get prop1() { return this._prop1; },
set prop1(value) { this._prop1 = value; /*Listener code can go here*/ }
};
回答by Richard Christensen
If you want to fire off events when an objects variable changes, you could set up a small Observer pattern for that obj.
如果您想在对象变量更改时触发事件,您可以为该对象设置一个小的观察者模式。
var MyVar = {
prop1: "Foo",
prop2: "Bar",
events: {},
setProp1: function(prop1) {
this.prop1 = prop1;
this.notify('prop1', this.prop1);
},
setProp2: function(prop2) {
this.prop2 = prop2;
this.notify('prop2', this.prop1);
},
addEvent: function(name) {
if (typeof this.events[name] === "undefined") {
this.events[name] = [];
}
},
register: function(event, subscriber) {
if (typeof subscriber === "object" && typeof subscriber.notify === 'function') {
this.addEvent(event);
this.events[event].push(subscriber);
}
},
notify: function(event, data) {
var events = this.events[event];
for (var e in events) {
events[e].notify(data);
}
}
};
var Prop1 = {
notify: function() {
alert('prop1 changed');
}
};
var Prop2 = {
notify: function() {
alert('prop2 changed');
}
};
$(document).ready(function(){
MyVar.register('prop1',Prop1);
MyVar.register('prop2',Prop2);
MyVar.setProp1('New Var');
MyVar.setProp2('New Var');
});
Usage instead of setting the object property directly you use a setter method which then fires off a notify event to other objects that are watching it.
用法而不是直接设置对象属性,而是使用 setter 方法,然后向正在监视它的其他对象触发通知事件。
回答by Mohammed Joraid
I know this is an old question, but if you are doing this for debugging proposes, you can add a listener using your debugging tool at your browser
same way you debug script.
我知道这是一个老问题,但是如果您这样做是为了调试建议,您可以使用debugging tool at your browser
与调试脚本相同的方式添加一个侦听器。
Personally I'm using Firebug
in Firefox, once opened, go to DOM tab, search for your variable, then (similarly to adding a breakpoints to script) add a breakpoints
. It will break and scroll to the specific line of code that's going to process the change on the variable.
我个人Firebug
在 Firefox 中使用,一旦打开,转到 DOM 选项卡,搜索您的变量,然后(类似于向脚本添加断点)添加一个breakpoints
. 它将中断并滚动到将处理变量更改的特定代码行。
Check this out -> Firefox FIREBUGOR Google Chrome DEVELOPER TOOL