Google analytics code

Monday, March 1, 2010

Flash / Flex / ActionScript: Using IResponder instead of EventListeners

Using addEventListener is a popular way of of waiting for a response from a server. I've run into issues using this when a server returns the same response for all methods. Many of the listener methods are tripped for the wrong response. The easy way to avoid this is to use an IResponder.

Here is an example using the HTTPService object. You should be able to use the same steps on a method that returns an AsyncToken.

var asyncToken:AsyncToken;
var internalIResponder:IResponder;
...
asyncToken = _httpService.send();
internalIResponder = new AsyncResponder(onHTTPServiceSuccess, onHTTPServiceFault, asyncToken);
asyncToken.addResponder(internalIResponder);

When send is called it will return an AsyncToken. We can attach an IResponder object to the AsyncToken that will handle the success and fail cases for the response.

5 comments:

  1. Ever had a look at Cairngorm?

    Cairngorm is using IResponders exclusively since a long time.

    ReplyDelete
  2. I've heard of it, but never used it on a project. I'd like to check it out at some point.

    ReplyDelete
  3. You can also do in your listening function :

    srv.removeEventListener( theListenedEvent, theListeningFunction);

    ReplyDelete
  4. You can remove the listener if it is a member/field variable. If it's local to the method you can't remove it later.

    ReplyDelete
  5. Thank you. I was having this exact problem (multiple listeners being called from HTTPService result). I had tried using removeEventListener, but when you're firing off a bunch of asynchronous requests, you might inadvertently remove the listener before another async request has started/completed.

    ReplyDelete

If you found this page useful, or you have any feedback, please leave a comment.