用JavaScript编写自定义事件调度程序? [英] Write a custom event dispatcher in JavaScript?
问题描述
如何在JavaScript中向我自己的类的对象添加事件侦听器和调度事件?
在ActionScript 3中我可以简单地从Sprite / DisplayObject继承并使用那里有可用的方法。像这样:
How can I add event listeners to and dispatch events from my objects of my own classes in JavaScript?
In ActionScript 3 I can simply inherit from Sprite/DisplayObject and use the methods available there. Like this:
// ActionScript-3:
// I can add event listeners to all kinds of events
var mySprite: Sprite = new MySprite();
mySprite.addEventListener("my_menu_item_click", onMenuItemClick);
// later I can dispatch an event from one of my objects
mySprite.dispatchEvent(new Event("my_menu_item_click", ...));
我想在JavaScript中使用相同的功能。到目前为止,我知道 window.addEventListener(...)
和 document.addEventListener(...)
。到目前为止,我在JavaScript中拥有自己的Sprite类,我想用它来发送我自己的事件。
I would like to have the same in JavaScript. Until now I know about window.addEventListener(...)
and document.addEventListener(...)
. I have my own Sprite class in JavaScript so far and I want to use it to dispatch my own events.
// JavaScipt:
function Sprite()
{
this.x = 0;
this.y = 0;
// ...
}
因为这两种语言看起来都很相似有些事件,我想我需要继承一些课程?或者我是否必须使用一些全局变量,如窗口和/或文档?
Since both languages seem so "alike" with events I guess I need to inherit from some class? Or do I have to use some of the global variables like window and/or document?
我在这里使用HTML5。我只有1个画布和一堆精灵被吸引到用户输入。我想要一个精灵A来订阅另一个精灵B的事件。但不是到第三个精灵C。
I'm working with HTML5 here. I have only the 1 canvas and a bunch of sprites that are drawn to it and react to user input. I would like one sprite A to subscribe to events of another sprite B. But not to the third sprite C.
推荐答案
我尝试将方法添加到我的Sprite类中并成功。
当然还没有完成,但至少它可以工作。
这就是我想要的。
I tried to add the methods into my Sprite class and succeeded.
Of course not finished yet, but at least it works.
It's what I was looking for.
function Sprite()
{
// ...
this.eventListeners = new Array();
this.addEventListener = function(type, eventHandler)
{
var listener = new Object();
listener.type = type;
listener.eventHandler = eventHandler;
this.eventListeners.push(listener);
}
this.dispatchEvent = function(event)
{
for (var i = 0; i < this.eventListeners.length; i++)
if (event.type == this.eventListeners[i].type)
this.eventListeners[i].eventHandler(event);
}
}
这篇关于用JavaScript编写自定义事件调度程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!