Monday, July 19, 2010

Useful Closures use-cases in Flex

As flex is based on Actionscripts 3, it is possible to leverage some of the features of an ECMA-based language not readily available in strongly-typed languages.  Most Java developers will probably ignore the ability to use powerful features such as closures when the use-case simply makes sense. Consider the following:


Function Handlers
In most cases where a function handler is needed, this tip may be very useful, particularly when you don't want to maintain "any" state within the object you create. For example consider the case of an HTTPService call.
var svc:HTTPService = new HTTPService();
  svc.url = "http://yourdomain/rest"; 
  svc.addEventListener(ResultEvent.RESULT, 
                       successHandler);

In this plain vanilla example, you need to have a successHandler method with the following signature:
public function successHandler(event:Result):void {
    // your implementation here
  }
What if you needed to add a handler with additional parameters. Then you can leverage the dynamic nature of actionscript and write a closure like:
svc.addEventListener(ResultEvent.RESULT, 
                       function (event:ResultEvent):void {
       handleResult(event, foo);
  });
and your new method to handle the result event will be:
public function handleResult(event:Result, 
                               foo:Object):void {
    // your implementation here
  }

ResourceManager use in ActionScript
Most tutorials I read were about the ability to do localization in Flex using the ResourceManager.getString() operation. In the case of binding to changes in the locale (as in the case of English to Spanish change), the recommended way to change is the following:



This way, the app if completely localized. Notice that binding to the value of the returning string is fulfilled by the use of the curly bracket notation.  I found few discussion of what happens when the Label is created programatically (in actionscript). BindingUtils is a nice component from the Flex API that is aimed to solve the problem as you write a closure for the chain parameter (destination to be bound to). Here is an example:

BindingUtils.bindProperty(this, 
     "mylocalProperty", 
     ResourceManager.getInstance(),
     {  name:"getString",
        getter: function (rm:IResourceManager):String {
             return rm.getString('mybundle', 'property');
             }
     });
According to the API, the 3rd parameter can be an object of the form {name:"property", getter:"function(host)..." which means that the getter can now be a closure of your choice.

Hope this helps!

No comments: