2 Replies Latest reply on Apr 13, 2009 8:51 AM by Gregory Lafrance

    What is better: Handling events in MXML or Actionscript?

    pxstein Level 1

      At least from "Flex in a week" tutorial I learned that I can handle events in two ways:

       

      1.) by MXML script blocks without Actionscript

       

      or

       

      2.) By ActionScript Blocks

       

      What is intended to be the future, better, recommended way of coding:

       

      First or second approach?

       

      Is there a difference in performance/stability/compatibility?

       

      Peter

        • 1. Re: What is better: Handling events in MXML or Actionscript?
          Michael Borbor Level 4

          I don't understand what you mean by script blocks without ActionScript. But if you have a Button with an id "myButton" and you write inside the click event "trace(I was click);"

           

           <mx:Button id="myButton" 
                   click="trace('I was clicked')" label="Click me" />
          

          That little piece of code that you wrote inside the click event is ActionScript. It's always recommended to separate mxml from actionscript for reuse, maintainability.

          • 2. Re: What is better: Handling events in MXML or Actionscript?
            Gregory Lafrance Level 6

            It is okay to handle events in MXML for simple handling, like the following:

             

            <mx:Button id="myBtn" label="Click Me" click="myHTTPServiceRequest.send();"/>

             

            but in general it is better to simply specify the handler function in the MXML tag and define the handler in AS in a <mx:Script> tag, otherwise your MXML gets messy.

             

            There are some circumstances where it might be better to use addEventListener() in an init() method assigned to the application or component root tag creationComplete event, rather than assign event listeners in MXML tags. This is because using addEventListener() allows you to use removeEventListener() if necessary, which you cannot do if you add an event listener in MXML. Using one removeEventListener() call for each addEventListener() call is important when you set objects to null. If there are any references to the object or to and of its children, etc. it may not a candidate for garbage collection.

             

            See this link for great info on this topic:

             

            Registering Event Handlers