Custom Event Dispatching
-
10-06-2021 - |
Question
I'm trying to fire an event from sub class, I have 3 classes; EventHandler, MainClass, SubClass
EventHandler.as
public class EventHandler extends Event
{
public static const TEST_EVENT:String = "Test";
public function EventHandler($type:String, $params:Object, $bubbles:Boolean = false, $cancelable:Boolean = false)
{
super($type,$params, $bubbles, $cancelable);
this.params = $params;
}
public override function clone():Event
{
return new EventHandler(type, this.params, bubbles, cancelable);
}
}
MainClass.as
public function MainClass()
{
addEventListener(EventHandler.TEST_EVENT, testFunc);
}
private function testFunc(e:EventHandler){
trace("OK");
}
SubClass.as
private function CustomFunction(event:MouseEvent):void {
dispatchEvent(new EventHandler(EventHandler.TEST_EVENT,customObject));
}
I get VerifyError: Error #1063: flash.events::Event() What's wrong with my architect? Thanks!
Solution
Remove $params
from super($type,$params, $bubbles, $cancelable);
Like this:
public class EventHandler extends Event
{
public static const TEST_EVENT:String = "Test";
public function EventHandler($type:String, $params:Object, $bubbles:Boolean = false, $cancelable:Boolean = false)
{
super($type, $bubbles, $cancelable);
this.params = $params;
}
public var params:Object;
public override function clone():Event
{
return new EventHandler(type, this.params, bubbles, cancelable);
}
}
OTHER TIPS
Define a custom event like:
package com.mysite.events
{
import flash.events.Event;
public class PendingEvent extends Event
{
public var payload:Object = {};
public static const CONTENT_COMPLETE:String = "contentComplete";
public function PendingEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
public override function clone():Event
{
return new PendingEvent(type, bubbles, cancelable);
}
}
}
Elsewhere dispatch like:
var event:PendingEvent = new PendingEvent(PendingEvent.CONTENT_COMPLETE);
event.payload.someStuff = "stuff";
event.payload.moreStuff = "moreStuff"
dispatchEvent(event);
Then listen to it somewhere else:
this.component.addEventListener(PendingEvent.CONTENT_COMPLETE, componentContentComplete);
private function componentContentComplete(event:PendingEvent):void
{
// remove listener
this.component.removeEventListener(PendingEvent.CONTENT_COMPLETE, componentContentComplete);
// do something useful with payload
var payload:Object = event.payload;
trace(payload.someStuff); // stuff
trace(payload.moreStuff); // moreStuff
}
EDIT:
Obvioulsy you would not use an Object
for your payload, create another typed class of your choice and set props on that object instead, but you get the idea.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow