How to implement Custom Events?
How do I correctly implement custom events? I thought the following should work, but I never receive CustomEvent.READY in the main Model
package mvc
{
import flash.events.Event;
public dyn开发者_StackOverflowamic class CustomEvent extends Event
{
public static const MY_EVENT:String = "myEvent";
public static const READY:String = "ready";
public function CustomEvent(type:String)
{
super(type);
}
}
}
In the Model.as which extends AbstractModel which extends EventDispatcher
private function initWorld():void {
_worldModel = new WorldModel();
_worldModel.addEventListener(CustomEvent.READY, update);
}
Then in WorldModel.as which extends AbstractModel which extends EventDispatcher, I dispatch an event, but update is never called. why?
dispatchEvent(new Event(CustomEvent.READY));
_worldModel.dispatchEvent(new CustomEvent(CustomEvent.READY));
You must instantiate a CustomEvent, not an Event. Big difference.
You could also use your custom event to pass additional parameters with the dispatched event, which will prove amazingly handy if you make use of your CustomEvent heavily
package com.b99.events
{
import flash.events.Event;
/**
* ...
* @author bosworth99
*/
public class AppEvents extends Event
{
public static const APP_READY :String = "application ready";
public static const XML_LOADED :String = "XML has loaded";
public static const CHANGE_COMPLETE :String = "state change complete";
public static const PAGE_ADDED :String = "page content added";
public static const PAGE_REMOVED :String = "page content removed";
public static const LIBRARY_LOADED :String = "external library loaded";
public static const IMAGE_LOADED :String = "external image loaded";
public static const LOAD_ERROR :String = "external load failed";
public var arg:*;
public function AppEvents(type:String, bubbles:Boolean = false, cancelable:Boolean = false, ...a:*)
{
super(type, bubbles, cancelable);
arg = a;
}
override public function clone():Event
{
return new AppEvents(type, bubbles, cancelable, arg);
}
}
}
You can then pass any number of arguments along to a receiving function:
this.dispatchEvent(new AppEvents(AppEvents.LIBRARY_LOADED, false , false, _name, _library, _names));
And access them in the recieving function as an array.
private function onLibraryLoad(e:AppEvents):void
{
_digestExternalLib.removeEventListener(AppEvents.LIBRARY_LOADED, onLibraryLoad);
var currentIndex:int = AppData.navLocations.indexOf(e.arg[0], 0);
AppData.libraries.push(e.arg[0]);
AppData.libraryCon.push(e.arg[1]);
AppData.libraryNames.push(e.arg[2]);
}
I yanked this from a functioning project... but you should be able to gather the important bits... Good luck!
I don't really see anything wrong with the code. Just to test, try adding this statement at the end of initWorld() method:
_worldModel.dispatchEvent(new Event(CustomEvent.READY));
If your update() method is called, that would indicate that your existing dispatchEvent() method isn't being called.
精彩评论