【问题标题】:Action Script 3 code design questionAction Script 3 代码设计题
【发布时间】:2009-11-19 08:33:49
【问题描述】:

我有一个简单的 flex3 项目,其中包含 mxml 文件(其中包含一些文件)和 FMSConnection.as

我有这样的事情

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

【问题讨论】:

    标签: apache-flex actionscript-3


    【解决方案1】:
    //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));
        }
    }
    

    如果需要,您可以调度自定义事件并将消息存储在其中,而不是声明 lastMessage 变量。

    //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));
        }
    }
    

    在这种情况下,不需要重写 clone 方法,但在使用自定义事件时遵循这种做法是一种很好的做法。如果您不覆盖 clone 方法,您将在尝试从事件处理程序重新调度自定义事件时收到运行时错误。

    【讨论】:

    • 更新了帖子 - 还更正了我首先发布的代码中的一个小错误 - onMessage 中的事件类型应该是普通的 Event 而不是 MessageEvent
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多