开发者

how to get data from an event in another class in flash as3?

I have a class called socket.as and is responsible for socket connection etc. It has an event listener onSocketData, which is called whenever data is received. In my main class, Main.as, i have instantiated an object of socket class.

How can I get data from socket class? Do i have to create a custom event in Main.as that should be triggered by socket class? Thank you.

below is the event listener from socket class:

private function onSocketData(event:ProgressEvent):void <br>
{
   //string sent over serial port.   
   var d开发者_高级运维ata:String = _socket.readUTFBytes( _socket.bytesAvailable );  

   var direction:int = 0;  

   buffer += data;  

 while((index = buffer.indexOf(EOL_DELIMITER)) > -1)
 {
  msg = buffer.substring(0, index-1);
  len = (buffer.indexOf(EOL_DELIMITER)) - 1;

  //remove the message from the buffer
  buffer = buffer.substring(index + 1);

  if ( msg != "off" )
  {
   button = parseInt(msg.substr(6, (len-8)));

   trace("Socket Data: " + msg + ", Button: " + button);
  }
 }
}


As you mention , you could create a CustomEvent that will be triggered by the Socket class or you could dispatch an Event from the Socket class , whenever data is available and use a getter to retrieve the variable.

I've answered a similar question here:
AS3 Passing data between objects/classes


Well, if you just want to get data out, you can store it in an array in your class, and then have a method that pulls it out.

If, instead, you want to push up an event to Main.as, then you will need to create a custom event.

The easiest way to do this is to derive your class from EventDispatcher.

Then, when you want to fire an event, you just call super.dispatchEvent(new CustomEvent(payload)) where CustomEvent is a class of yours that derives from Event.

The general pattern would look like this:

Create a custom event... unless an existing event class makes sense... then just reuse something else.

public class SocketEvent extends Event {
    public var payload:String;
    public function SocketEvent(payload:String, bubbles:Boolean=false, cancelable:Boolean=false) {
        super(Socket.EVENT_NAME, bubbles, cancelable);
        this.payload = payload;
    }
}

Then, the class that fires the event looks like this:

public class Socket extends EventDispatcher {
    public static const EVENT_NAME:String = "EVENT_NAME";

    private function fireTheEvent(payload:String):void {
        dispatchEvent(new SocketEvent(payload));
    }
}

Finally, to use it in Main.as, you would do this:

private var socket:Socket = new Socket();
socket.addEventListener(Socket.EVENT_NAME, actionHandler);

Note that this is NOT the only way to fire an event. Another way would be to implement IEventDispatcher in terms of the static EventDispatcher methods... but that is a different example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜