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", ...));
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?
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.