Omu
Omu

Reputation: 71228

Action Script 3 code design question

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 ?    
   }
}

Upvotes: 1

Views: 121

Answers (1)

Amarghosh
Amarghosh

Reputation: 59451

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

Upvotes: 3

Related Questions