When you use a class from the Flex framework that does an asynchronous call, you can use the AsyncToken that the call returns to save values/objects that you need when the result event is triggered.
Let’s look at this code:
So, we have two functions. The first, getData() creates a HTTPService, attaches an event listener for the result event, and then makes a call to the server. When it makes a call, an AsyncToken is returned. I can use this token to store some info I need in the result listener. The second function is the definition of the result listener. When this function is called, you can access the AsyncToken from the property token from event: event.token. Having the token, it is easy to retrieve the data that I stored when I made the call to the service.
Why is that useful? Sometimes you want to be able to associated some data to a particular call, so when result event is called, you are able to take a different actions based on the data passed.
Unfortunately, when you do a call to a class from Flash, for example, flash.net.URLLoader you don’t have this AsyncToken returned. Consider the following code:
How do you pass your data between the call and the result for objects that are not using AsyncToken? One simple way is to extend the object you want to use, and add one property to store an object. Let’s do this for the URLLoader class:
Now, let’s see how you can use this object to do asynchronous calls and still be able to pass data:
When I create the custom loader object, I pass a reference to the data object that I want to retrieve when the loader has the response (this object is stored using the _data property from MyLoader). When the complete event is reached, using the target property on the event object, I retrieve the MyLoader object that made the call . Having the loader object, I can access the data property to retrieve the original data I stored.