Custom Flash/Flex Event object
I'm in a Flex Mobile application project. I need to dispatch an event to the FlexGlobals.topLevelApplication and it has to contain a custom message.
I'm trying to make an object and dispatch it like this:
//create the event Object
var receivedObjMsg:Object = new Object();
receivedObjMsg.name = "receivedMessage";
receivedObjMsg.message = messagevarhere;
FlexGlobals.topLev开发者_运维技巧elApplication.dispatchEvent(receivedObjMsg);
and then receive it like this on the other view like this:
FlexGlobals.topLevelApplication.addEventListener("receivedMessage", receiveMsgHandler);
protected function receiveMsgHandler(event:Event):void
{
trace("IT WORKED!");
}
But its saying it cant make an object into an event:
Type Coercion failed: cannot convert Object@5a507911 to flash.events.Event.
I also tried putting this in the bottom of the main application mxml where i created the event;
<fx:Metadata>
[Event(name="receivedMessage", type="flash.events.Event")]
</fx:Metadata>
I can't really seem to find an example that demonstrates what im trying to do. Any ideas how I can get this to work?
dispatchEvent
takes an Event
Create your own class that extends Event
and then dispatch that.
Take a look at this article that discusses how to dispatch a custom event.
class MyOwnEvent extends Event
{
public static const RECEIVED_EVENT:String = "receivedEvent";
public string name;
public string message;
public MyOwnEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false)
{
}
}
And when you want to dispatch it.
var myevent:MyOwnEvent = new MyOwnEvent(MyOwnEvent.RECEIVED_EVENT);
myevent.name = "whatever";
myevent.message = "another whatever";
FlexGlobals.topLevelApplication.dispatchEvent(myevent);
From the topLevelApplication, make sure that you listen for the same event.
FlexGlobals.topLevelApplication.addEventListener(MyOwnEvent.RECEIVED_EVENT, receiveMsgHandler);
In the receiveMsgHandler
take an object of type MyOwnEvent
.
protected function receiveMsgHandler(event:MyOwnEvent):void
{
trace(event.name);
trace(event.message);
}
dispachEvent()
only accepts an Event
object. You'll need to make your own class ReceivedObjMsg
.
Details on creating your own class in an answer on a previous question of yours.
Your issue is basically here:
var receivedObjMsg:Object = new Object();
receivedObjMsg.name = "receivedMessage";
receivedObjMsg.message = messagevarhere;
FlexGlobals.topLevelApplication.dispatchEvent(receivedObjMsg);
Parsing Object
through dispatchEvent()
精彩评论