How to implement Custom Events? - actionscript-3

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 dynamic 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.

Related

Should a custom event have get methods?

I created some custom events in a desktop application and gave it some get methods in order to grab the data that is associated with the event. It seems odd to be calling 'get' methods on an event. Is this bad programming practice, should I make the event properties public instead?
Here is my custom event...
package classes.events
{
import flash.events.Event;
public class ListItemClickedEvent extends Event
{
public static var PROJECT_CHOSEN:String = "project_chosen";
private var projectName:String;
private var projectLabel:String;
private var projectFolder:String;
public function ListItemClickedEvent(type:String, bubbles:Boolean = true,
cancelable:Boolean = false, pName:String = null,
pLabel:String = null, pFolder:String = null){
super(type, bubbles, cancelable);
projectName = pName;
projectLabel = pLabel;
projectFolder = pFolder;
}
override public function clone():Event{
return new ListItemClickedEvent(type, bubbles, cancelable);
}
public function getProjectName():String{
return projectName;
}
public function getProjectLabel():String{
return projectLabel;
}
public function getProjectFolder():String{
return projectFolder;
}
}
}
Flex events like ListEvent or MenuEvent simply use public variables, but feel free to use any access practice you like: getter functions, properties or public variables. It's your class and you can use your own style.

is it possible to change data provider of flex chart from a seperate ActionScript class?

Im trying to change flex chart data provider from seperate action script class? is it possible. i did not find any method to do that. any ideas guys ?
Yes you can. For that you need to have a reference to dataprovider of chart and it should be bindable. It means when you update dataProvider you view also will be update ( chart in this case ).
If it doesn't help you, I would see your code.
Yes, you can. A nice clean way is to have a custom event dispatcher facade:
package com.app.facades
{
import flash.events.Event;
import flash.events.EventDispatcher;
[Event(name="showDataInGrid" , type="com.app.events.GridEvent")]
public class GridFacade extends EventDispatcher
{
private static var _instance:GridFacade;
public function GridFacade(lock:SingletonLock, target:IEventDispatcher=null) {
super(target);
if(!(lock is SingletonLock)) {
throw(new Error("GridFacade is a singleton, please do not make foreign instances of it"));
}
}
public static function getInstance():GridFacade {
if(!_instance) {
_instance = new GridFacade(new SingletonLock());
}
return _instance;
}
}
}
class SingletonLock{}
create a dispatchable event like so:
package com.app.events {
import flash.events.Event;
import flash.events.IEventDispatcher;
public class DispatchableEvent extends Event implements IDispatchableEvent {
protected var _dispatcher:IEventDispatcher;
public function DispatchableEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
public function dispatch():void
{
_dispatcher.dispatchEvent(this);
}
}
}
then have a custom GridEvent like so:
package com.app.events {
public class GridEvent extends DispatchableEvent {
public static const SHOW_DATA_IN_GRID:String = "showDataInGrid";
public var data:Object;
public function GridEvent(type:String,
data:ArrayCollection = null,
bubbles:Boolean=false,
cancelable:Boolean=false) {
super(type,bubbles,cancelable);
_dispatcher = GridFacade.getInstance();
this.data = data;
}
}
}
then listen for the showDataInGrid event in the scope of your grid component:
...
GridFacade.getInstance().addEventListener(GridEvent.SHOW_DATA_IN_GRID, onShowDataInGrid);
...
protected function onShowDataInGrid(event:GridEvent):void {
myGrid.dataProvider = event.data;
// refresh the collection so that the component will display the new data
event.data.refresh();
// remember to reset any data specific stuff you may have set in the grid component before doing this.
}
to actually change the data, in any class you wish do the following:
(new GridEvent(
GridEvent.SHOW_DATA_IN_GRID,
someCollectionToShowInTheGrid,
)).dispatch();
And watch the magic! :)
good luck!

Haxe: Return value of field

For some reason, I can't modify the value of a field in Haxe. Of course, this doesn't seem to be affecting all of my fields, just this one. Here's (what I'm pretty sure is) the applicable code. First, in the parent class:
class TopMenu extends Sprite
{
public function new()
{
super();
init();
}
private function init()
{
var tempField:BitmappedTextField = new BitmappedTextField( "File", 100, false );
trace( tempField.textWidth );
}
}
Then, in the child class:
class BitmappedTextField extends Sprite
{
private var _fieldText:String;
private var _fieldWidth:Int;
private var _addToStage:Bool;
public var textWidth:Int;
public function new( thisText:String, thisWidth:Int = 100, adTStg:Bool = true )
{
super();
_fieldText = thisText;
_fieldWidth = thisWidth;
_addToStage = adTStg;
textWidth = 55;
init();
}
public function init()
{
textWidth = 777;
}
}
I would expect the trace statement to return 777, but instead it will always return 55. In fact, no matter what I do, I can't seem to modify a field outside of the constructor class and then retrieve that value via the parent class. There's something horribly simple I must be missing, but I just can't figure it out. Maybe it has to do with the way Haxe uses getters and setters? Any help is appreciated, thank you.
I cant reproduce your problem however and you are missing a ; and a super call.
Try this code.
package;
import nme.display.Sprite;
import nme.display.MovieClip;
class HelloWorld extends MovieClip
{
public function new( )
{
super();
var tempField:BitmappedTextField = new BitmappedTextField();
trace( tempField.textWidth );
}
}
class BitmappedTextField extends Sprite
{
public var textWidth:Int;
public function new( )
{
super();
textWidth = 55;
init( );
}
public function init( )
{
textWidth = 777;
}
}

In ActionScript 3.0, can you use addEventListener for one class to react to the function call of another class?

I know how to use addEventListener for one class to react to another class's button being clicked on. What if you want to use it for a more general purpose than that? What if you want to use it to react to one of the member functions of the other class being called? Is there a syntax for that? Thanks!
Edit: Please note that I have already Googled for the answer.
If you want to listen for another class' member function call, you need that function call to dispatch an Event. This is as simple as...
Listener Class
addEventListener("customEvent", listenerFunc);
Dispatcher Class (extends EventDispatcher / implements IEventDispatcher)
dispatchEvent(new Event("customEvent"));
As long as the listener class is above the dispatcher class in the object hierarchy, this will work perfectly. If not, you may want to use some sort of Global EventDispatcher class and register all listeners on that.
You can create your own events and dispatch them from the other class and listen to them in your listening class. Here is some code
In class A (assuming it inherits EventDispatcher)
public function classAMethod():void
{
dispatchEvent(new Event("someCustomTypeForEvent"));
}
In class B (assuming it has a reference to Class A)
public function classBMethod():void
{
classA.addEventListener("someCustomTypeForEvent",customHandler);
}
public function customHandler(e:Event):void
{
trace("handle event");
}
It's like in JAVA for java.awt.Component instances and all Objects that extends java.awt.Component; in AS3 you may add Listeners to all Objects that extends flash.display.Sprite instances which implements methods of IEventDispatcher for you...
So, If you have a class which do not extends flash.display.Sprite, you'll have to extend EventDispatcher in order to add Listeners to your instances and handle Events...
If the class may not extend EventDispatcher, you'll have to implement the IEventDispatcher.
Here is a [class MainClass] that extends [class MovieClip]
This MainClass instance, creates :
An instance of [class ObjectA] which extends [class Object] and implements IEventDispatcher,
An instance of [class ObjectB] which extends [class EventDispatcher]
Here is the code that use the extension method and the implementation method :
I hope this quick done example will help you...
(And sorry for my English, this is not my native language.)
in MainClass.as :
package com
{
import flash.utils.getDefinitionByName;
import flash.display.MovieClip;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.utils.getQualifiedSuperclassName;
import com.classes.ObjectA;
import com.classes.ObjectB;
import flash.events.Event;
public class MainClass extends flash.display.MovieClip
{
private static const DEBUG:Boolean = true;
private static var instance:MainClass;
private static var instanceOfA:ObjectA;
private static var instanceOfB:ObjectB;
public function MainClass()
{
MainClass.debug("MainClass constructor called");
MainClass.debug(getClassInformations(MainClass));
MainClass.debug(getClassInformations(ObjectA));
MainClass.debug(getClassInformations(ObjectB));
instanceOfA = new ObjectA();
instanceOfB = new ObjectB();
instanceOfA.addEventListener(ObjectA.DO_SOMETHING_EVENT,onInstanceOfA_doSomething,false,0,false);
instanceOfB.addEventListener(ObjectB.DO_SOMETHING_EVENT,onInstanceOfB_doSomething,false,0,false);
instanceOfA.doSomething();
instanceOfB.doSomething();
}
public static function onInstanceOfA_doSomething(e:Event):void
{
trace("An ObjectA has Dispatched An Event of type \"" + e.type + "\"" + " on " + e.target);
}
public static function onInstanceOfB_doSomething(e:Event):void
{
trace("An ObjectB has Dispatched An Event of type \"" + e.type + "\"" + " on " + e.target);
}
public static function getDebugMode():Boolean
{
return DEBUG;
}
public static function debug(string:String)
{
if (getDebugMode())
{
trace(string);
}
}
public static function getClassInformations(someClass:Class):String
{
var clss:Object = null;
var supClss:Object = null;
clss = getDefinitionByName(getQualifiedClassName(someClass));
try
{
supClss = getDefinitionByName(getQualifiedSuperclassName(someClass));
}
catch (e:ArgumentError)
{
// Has no superClass (ex:Object)
}
if (supClss != null)
{
return ("class " + clss + " extends " + supClss);
}
else
{
return ("class " + clss);
}
}
}
}
in ObjectB.as (simplest way):
package com.classes{
import com.MainClass;
import flash.events.EventDispatcher;
import flash.events.Event;
public class ObjectB extends EventDispatcher {
public static var DO_SOMETHING_EVENT:String = "do_something_event";
private var onDoSomethingEvent:Event = new Event(DO_SOMETHING_EVENT,false,false);
public function ObjectB() {
MainClass.debug("constructor ObjectB called");
}
public function doSomething():void{
this.dispatchEvent(onDoSomethingEvent);
}
}
}
in ObjectA.as (there you must implement all the methods of the interface IEventDispatcher):
package com.classes
{
import com.MainClass;
import flash.events.IEventDispatcher;
import flash.events.EventDispatcher;
import flash.events.Event;
public class ObjectA implements IEventDispatcher
{
public static var DO_SOMETHING_EVENT:String = "do_something_event";
private var onDoSomethingEvent:Event = new Event(DO_SOMETHING_EVENT,false,false);
private var dispatcher:EventDispatcher;
public function ObjectA()
{
dispatcher = new EventDispatcher(this);
MainClass.debug("constructor ObjectA called");
}
public function doSomething():void
{
this.dispatchEvent(onDoSomethingEvent);
}
public function addEventListener(
event_type:String,
event_listener:Function,
use_capture:Boolean = false,
priority:int = 0,
weakRef:Boolean = false
):void
{
// implements addEventListener here
dispatcher.addEventListener(event_type, event_listener, use_capture, priority, weakRef);
}
public function dispatchEvent(e:Event):Boolean
{
// implements dispatchEvent here
return dispatcher.dispatchEvent(e);
}
public function removeEventListener(
event_type:String,
event_listener:Function,
use_capture:Boolean = false
):void
{
// implements removeEventListener here
dispatcher.removeEventListener(event_type, event_listener, use_capture);
}
public function hasEventListener(type:String):Boolean
{
// implements hasEventListener here
return dispatcher.hasEventListener(type);
}
public function willTrigger(type:String):Boolean
{
// implements willTrigger here
return dispatcher.willTrigger(type);
}
}
}
Note that if you extend an EventDispatcher, you may also want to override some methods.
In this case, you must use the "override keyword as :
public override function dispatchEvent (e:Event):Boolean {
// a method of EventDispatcher may be overridden if needed !
// do what you need HERE...
return dispatchEvent(e);
}
In AS3 you must specify the override keyword or you'll get an Error 1024:
"Overriding a function that is not marked for override."
When you create a new EventDispatcher through implement or extend, you may also specify additional arguments and methods to this object as:
public function ListenerObject (v:View,m:Main) {
dispatcher = new EventDispatcher(this);
view = v;
master = m;
}
public function getView ():View {
return view;
}
public function getMain ():Main {
return master;
}
then use those methods in the callback method as :
public function callback(e:Event):void{
e.target.getView ();
//...
}

Override Clone() in custom event for AS3... need help

I have created a custom even class which is pretty basic. But when calling an event and then relaying that event to another class I have encountered the "cannot transform thisEvent into thisOtherEvent" error.
I realize this is because I needed to override the Clone function in my custom event like so:
package com
{
import flash.disply.*;
import flash.events.Event;
public class MyCustomEvents extends Event
{
public static const SOME_EVENT:String = "some_event";
public var info:Object;
public function MyCustomEvents($type:String, $info:Object,$bubbles:Boolean = false, $cancelable:Boolean = false)
{
super($type, $bubbles, $cancelable);
this.info = $info;
}
public override function clone():Event {
return new MyCustomEvents($type, $bubbles, $cancelable);
}
}
}
However I am still getting this error when I dispatch the event. Anything else I might be missing?
here is the error:
TypeError: Error #1034: Type Coercion failed: cannot convert com.greensock.events::TransformEvent#d8df709 to com.customEvents.MyCustomEvents.
I tried casting the event in the code like so:
var deleteImgEvent:MyCustomEvent = new MyCustomEvent(MyCustomEvents.IMAGE_DELETE, {imgData: getImg}, true, false); this.dispatchEvent(deleteImgEvent as MyCustomEvents);
Still no luck.
UPDATE:
Ok, seems like the problem is in the greensock Transform library. When the event handler for my custom event is called, I run a function of the TransformManager class.
_manager.deleteSelection();
Inside that class it dispatched a TransformEvent. Not sure why, but it is reading that delete event as a MyCustomEvent.
/**
* #usage
* var myEvent:CustomEvent = new CustomEvent(CustomEvent.EVENT_TYPE_A, { integerRelatedToEvent: 5, stringRelatedToEvent: 'easy' });
* addEventListener(CustomEvent.EVENT_TYPE_A, traceCustomEvent);
* dispatch(myEvent);
* function traceCustomEvent ($e:CustomEvent):void {
* trace($e.type);
* }
*/
package {
import flash.events.Event;
public class CustomEvent extends Event {
// Types:
public static const EVENT_TYPE_A:String = 'CustomEvent.EVENT_TYPE_A';
public static const EVENT_TYPE_B:String = 'CustomEvent.EVENT_TYPE_B';
// Components:
private var _customDatum:Object;
public function get customDatum ():Object { return _customDatum; }
public function CustomEvent ($type:String, $customDatum:Object) {
super($type);
_customDatum = $customDatum;
}
public override function clone ():Event {
return new CustomEvent(type, _customDatum);
}
}
}
"When creating your own custom Event
class, you must override the inherited
Event.clone() method in order for it
to duplicate the properties of your
custom class. If you do not set all
the properties that you add in your
event subclass, those properties will
not have the correct values when
listeners handle the redispatched
event."
package com.events;
{
import flash.events.Event;
public class XMLLoaderEvent extends Event
{
public static const XML_LOADED:String = "XML_Loaded";
public var data:*;
public var properties:Object;
public function XMLLoaderEvent( type:String,_data:*,bubbles:Boolean = false,cancelable:Boolean = false):void
{
super( type, bubbles, cancelable );
data = _data;
}
// Override clone
override public function clone():Event
{
return new XMLLoaderEvent( type, data, bubbles, cancelable);
}
}
}
Don't know if that's it but you have an extra parameter $info:Object into your custom event, but you don't pass it in your clone contructor.
return new MyCustomEvents(type, info, bubbles, cancelable);
I think you need the clone function to return a MyCustomEvents type. Not an Event type. And you need to add the info parameter as stated by the previous poster.
package com {
import flash.display.*;
import flash.events.Event;
public class MyCustomEvents extends Event {
public static const SOME_EVENT:String = "some_event";
public var info:Object;
public function MyCustomEvents($type:String, $info:Object,$bubbles:Boolean = false, $cancelable:Boolean = false) {
super($type, $bubbles, $cancelable);
this.info = $info;
}
public override function clone():MyCustomEvents {
return new MyCustomEvents(this.type, this.info, this.bubbles, this.cancelable);
}
}
}