我有一个包含事件侦听器的小部件:
var MyWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
this.addEventListeners([
{type: "tw-my-message", handler: "handleMyMessage"}
]);
};
并且,在同一个小部件的处理程序中
dispatchevent
:
MyWidget.prototype.handleMyMessage = function(event) {
...
this.dispatchEvent({type: "tw-my-message",param: "myparam"});
...
小部件侦听消息,然后将相同的消息(如果需要)传递给另一个小部件。
目前我必须使用两个相似的小部件(具有相同的功能)来监听不同的消息以避免小部件捕获自己的消息。
如何防止小部件捕获自己的消息?
您将需要传递事件的发布者,然后测试以确保事件发布者不是
this
。伪代码如下:
MyWidget.prototype.handleMyMessage = function(event) {
if (event.publisher === this)
return; // bail out, I published this event
// ...
};
dispatchEvent
的伪代码:
MyWidget.prototype.dispatchEvent = function(event) {
event.publisher = this;
// ... loop through subscribers and notify them
};