Friday, July 23, 2010

Flex 4: Best Practices for working with Events & Event Listeners

In Flex 4, it is easy to separate a component into an actionscript and mxml file, one for the logic and another for layout and skinning.

The actionscript file usually contains common framework methods such as partAdded(), partRemoved(), getCurrentSkinState() etc. whereas the skin file had all the visual components laid out.

Best Practices:
  1. When adding event listeners, always put them in using the partAdded() method and NOT in the constructor.
    Because if your component is included in multiple states, then somewhere along the line while you may be switching back & forth between the states, the event listener which was added in the constructor will just disappear and it will seem like any events that you are dispatching for that listener aren't getting caught and disappearing into limbo.
    A guess here is that even though the listener may not have had a weak reference, taking the component on & off the stage between state changes might cause its listener to get garbage collected.
    With the use of partAdded() method to add the event listener, this risk disappears because even if the same component is being taken off the stage and being put back then the framework will make sure to call partAdded() again. Unlike the constructor which had already been used to create the object.


Post a Comment