If say you wanted to dispatch an event from a child class, to it’s parent, the child class would need to extend EventDispatcher, or extend a class that extends EventDispatcher, like Sprite (as per @singmajesty’s suggestion).
The basic child class might look like this:
import openfl.events.EventDispatcher;
class SomeChildClass extends EventDispatcher {
public function new(target:IEventDispatcher = null) {
super(target);
}
}
Then in that child class, to dispatch an event, you might add a function like this:
private function announceSomeEvent():Void {
var evt:Event = new Event("someEvent");
dispatchEvent(evt);
}
In the parent class, to add a listener for that event:
var someChildClass:SomeChildClass = new SomeChildClass();
someChildClass.addEventListener("someEvent", someEventHandler);
private function someEventHandler(e:Event):Void {
trace("Event received");
}
If you’d like to send data or object references with the event, create a custom event by extending the Event class. I like doing this in most cases anyway, because it allows me to centrally define the event name, rather than relying on repeated strings like "someEvent"
(such as the example above), which can be prone to typos.
A custom event class might look like this. I’ve added the SOME_EVENT
event type, and a couple variables I can use for sending bits of data and object references.
import openfl.events.Event;
class MyCustomEvent extends Event
{
static public inline var SOME_EVENT:String = "someEvent";
public var someString:String;
public var someSpriteReference:Sprite;
public function new(type:String, bubbles:Bool=false, cancelable:Bool=false)
{
super(type, bubbles, cancelable);
}
}
To use this custom event in the child class now, inserting some data too:
private function announceSomeEvent():Void {
var evt:MyCustomEvent = new MyCustomEvent(MyCustomEvent.SOME_EVENT);
evt.someString = "Some string data.";
evt.someSpriteReference = someSprite;
dispatchEvent(evt);
}
And to listen for that event, and get the data it contains in the parent class:
var someChildClass:SomeChildClass = new SomeChildClass();
someChildClass.addEventListener(MyCustomEvent.SOME_EVENT, someEventHandler);
private function someEventHandler(e:MyCustomEvent):Void {
trace("Event received");
trace(e.someString);
trace(e.someSpriteReference);
}