views:

67

answers:

1

I have a simple flex3 project with and mxml file (with some as inside of it) and FMSConnection.as

I have something like this

public class FMSConnection extends NetConnection
{
   //this methods is called from the media server 
   public function Message(message:String):void
   {
       //how to display (add it to a textarea) this message, when this method is invoked ?    
   }
}
+3  A: 
//in the mxml, after FMSConnection is created:
fmsConn.addEventListener(FMSConnection.MESSAGE_RECEIVED, onMessage);

private function onMessage(e:Event):void
{
    fmsConn = FMSConnection(e.target);
    textArea.text += fmsConn.lastMessage;
}

//FMSConnection
public class FMSConnection extends NetConnection
{
    public static const MESSAGE_RECEIVED:String = "messageReceived";

    public var lastMessage:String;

    public function Message(message:String):void
    {
        lastMessage = message;
        dispatchEvent(new Event(MESSAGE_RECEIVED));
    }
}

Instead of declaring the lastMessage variable, you can dispatch a custom event and store the message in it if you want to.

//MsgEvent.as
public class MsgEvent extends Event
{
    public static const MESSAGE_RECEIVED:String = "messageReceived";
    public var message:String;
    public function MsgEvent(message:String, type:String)
    {
        super(type);
        this.message = message;
    }
    override public function clone():Event
    {
        return new MsgEvent(message, type);
    }
}

//in the mxml, after FMSConnection is created:
fmsConn.addEventListener(MsgEvent.MESSAGE_RECEIVED, onMessage);

private function onMessage(e:MsgEvent):void
{
    textArea.text += e.message;
}

//FMSConnection
public class FMSConnection extends NetConnection
{
    public function Message(message:String):void
    {
        dispatchEvent(new MsgEvent(message, MsgEvent.MESSAGE_RECEIVED));
    }
}

Overriding the clone method is not necessary in this case, but it's a good practice to follow while using custom events. If you don't override the clone method, you will get a runtime error while trying to redispatch the custom event from the event handler.

Amarghosh
can you show me how to create and dispatch a custom event
Omu
Updated the post - Also corrected a minor error in the code I posted first - the event type in `onMessage` should be plain `Event` rather than `MessageEvent`.
Amarghosh
thnx man, it works really good, awesome stuff !!!
Omu
Gotta give you an upvote just for being so thorough!!
onekidney