Reputation: 1683
I saw a question just like this, but the answer avoids the point with a callback function from the inside of class.
I did a class that reads a directory (ListaDir), make the request to a php server-side and process the answer. I wish to use like this:
var Lista:ListaDir = new ListaDir(urltophplibrarythatreadthedirectory); // this is working
Lista.addEventListener(Event.COMPLETE, myHandlerFunc); // this is the dream
function myHandlerFunc(e){
var Res:Object = e.target.data; // The answer in object containing the list and another info
}
Can be done like this? How?
Upvotes: 1
Views: 830
Reputation: 15955
Have your custom class extend EventDispatcher
and dispatch the desired event.
For example, for simple events like Event.Complete
simply dispatch a new Event
:
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
public class ListaDir extends EventDispatcher
{
public function dispatch():void
{
dispatchEvent(new Event(Event.COMPLETE));
}
}
}
If you need to dispatch an event with data, it may be optimal to create your event classes.
As an example, this CustomEvent
demonstrates a data
payload object:
package
{
import flash.events.Event;
public class CustomEvent extends Event
{
public static const COMPLETE:String = "COMPLETE";
public var data:*;
public function CustomEvent(type:String, data:*, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
if (data)
this.data = data;
}
}
}
When this class dispatches your CustomEvent
, it can send a payload of data:
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
public class ListaDir extends EventDispatcher
{
public function dispatch():void
{
var dataObject:Object = {name: "Example Data"};
dispatchEvent(new CustomEvent(CustomEvent.COMPLETE, dataObject));
}
}
}
Instantiate and create an event listener:
var listaDir:ListaDir = new ListaDir();
listaDir.addEventListener(CustomEvent.COMPLETE, completeHandler);
On complete, retrieve your data object:
protected function completeHandler(event:CustomEvent):void
{
var dataObject:* = event.data;
}
Upvotes: 3