7 Replies Latest reply on Feb 26, 2009 3:46 AM by blueMtnJava

    Easiest way to dispatch an event from a custom component

    Jed Schneider Level 1
      Hi,
      I have a custom login form and I would like to create an event that is fired when the authentication returns true from the server. Right now I have a result event in the component to handle the boolean condition from the webservice. I tried simply instantiating a new event (public var auth:Event = new Event (); )inside the component and dispatching that event from the logic of the resultEvent handler. But, from outside the component, there is no little lightning bolt symbol next to the auth event as there should be to call an event from the mxml.

      I want to be able to instantiate that event listener from the mxml and handle the event from outside the custom component. What blueprint should I use to encapsulate the event?

      Thanks,
      jed
        • 1. Re: Easiest way to dispatch an event from a custom component
          blueMtnJava Level 1
          Here is one approach:

          Step 1
          First, create an event manager class to listen for your event(s) - make the class a singleton. The following is an example which listens for 2 events, ProductClick and Authenticated

          package com.bloom.ecommerce.managers
          {
          import com.bloom.ecommerce.dto.User;
          import com.bloom.ecommerce.events.AuthenticatedEvent;
          import com.bloom.ecommerce.events.ProductClick;

          import flash.events.EventDispatcher;

          public class EventManager extends EventDispatcher
          {
          private static var instance:EventManager;

          public function EventManager()
          {
          }

          public static function getEventManager():EventManager {
          if (instance == null) {
          instance = new EventManager();
          }
          return instance;
          }

          public function triggerProductClick():void{
          var e:ProductClick = new ProductClick("productClick", false);
          this.dispatchEvent(e);

          }

          public function triggerAuthenticatedEvent(_user:User):void{
          var e:AuthenticatedEvent = new AuthenticatedEvent(_user,"authenticated", false);
          this.dispatchEvent(e);

          }


          }
          }


          Step 2
          - Instantiate the event manager component in the init() method of your custom component.
          - call a function to trigger your event when needed:
          - in the example below, an authenticated event is triggered after the user clicks OK to log in.

          <?xml version="1.0" encoding="utf-8"?>
          <mx:TitleWindow xmlns:mx=" http://www.adobe.com/2006/mxml"
          xmlns:m="com.bloom.ecommerce.managers.*"
          layout="vertical"
          width="350" height="200"
          title="Login"
          creationComplete="doInit();">
          <mx:Script>
          <![CDATA[
          import mx.managers.PopUpManager;
          import com.bloom.ecommerce.managers.EventManager;
          import mx.utils.StringUtil;
          import com.bloom.ecommerce.dto.User;


          private var eventManager:EventManager;

          private function doInit():void {
          // Center the TitleWindow container
          // over the control that created it.
          eventManager = EventManager.getEventManager();
          PopUpManager.centerPopUp(this);
          }

          private function processLogin():void {
          var user:User = new User();
          eventManager.triggerAuthenticatedEvent(user);
          }


          ]]>
          </mx:Script>

          <mx:Form>
          <mx:FormItem label="User Name">
          <mx:TextInput id="username" width="100%" text=""/>
          </mx:FormItem>
          <mx:FormItem label="Password">
          <mx:TextInput id="password" displayAsPassword="true" width="100%" text=""/>
          </mx:FormItem>

          />
          <mx:HBox>
          <mx:Spacer width="100"/>
          <mx:Button click="processLogin();" label="Submit"/>
          <mx:Button click="PopUpManager.removePopUp(this);" label="Cancel"/>
          </mx:HBox>
          <mx:Text id="errorMsg"
          fontFamily="Verdana,Arial"
          fontSize="8" fontWeight="bold"
          paddingLeft="40" paddingTop="5"

          />
          </mx:TitleWindow>




          Step 3:
          In the init() method of your main application,
          - get a reference to the event manager singleton
          - listen for the event you fire in your custom component
          - in the example below, the authenticated function listens for the authenticated event triggered in the LoginForm component


          import com.bloom.ecommerce.events.AuthenticatedEvent;
          import com.bloom.ecommerce.views.LoginForm;
          import com.bloom.ecommerce.managers.EventManager;

          private var eventManager:EventManager;

          private function init():void {
          eventManager = EventManager.getEventManager();
          eventManager.addEventListener("authenticated",authenticated);
          }

          private function authenticated(event:AuthenticatedEvent):void{
          //handle authencation here
          }




          • 2. Re: Easiest way to dispatch an event from a custom component
            Handycam Level 1
            Or

            this.dispatchEvent(new Event("myevent", true));
            • 3. Re: Easiest way to dispatch an event from a custom component
              Jed Schneider Level 1
              Yes, but how do you watch for that event outside the component. Thanks,
              • 4. Re: Easiest way to dispatch an event from a custom component
                Level 7

                "Jed Schneider" <webforumsuser@macromedia.com> wrote in message
                news:go3vcu$dvs$1@forums.macromedia.com...
                > Hi,
                > I have a custom login form and I would like to create an event that is
                > fired
                > when the authentication returns true from the server. Right now I have a
                > result
                > event in the component to handle the boolean condition from the
                > webservice. I
                > tried simply instantiating a new event (public var auth:Event = new Event
                > ();
                > )inside the component and dispatching that event from the logic of the
                > resultEvent handler. But, from outside the component, there is no little
                > lightning bolt symbol next to the auth event as there should be to call an
                > event from the mxml.
                >
                > I want to be able to instantiate that event listener from the mxml and
                > handle
                > the event from outside the custom component. What blueprint should I use
                > to
                > encapsulate the event?

                http://flexdiary.blogspot.com/2007/08/dispatching-events.html


                • 5. Re: Easiest way to dispatch an event from a custom component
                  Gregory Lafrance Level 6
                  Add an eventListener to the component parent:

                  myCompParent.addEventListener("myEvent", myEventHandler);
                  • 6. Re: Easiest way to dispatch an event from a custom component
                    Jed Schneider Level 1
                    Amy Blankenship was very helpful with her post at:
                    http://flexdiary.blogspot.com/2007/08/dispatching-events.html

                    Handycam was also correct, but I was missing the keystone i needed.

                    And Greg's idea would work, but I wanted to encapsulate the event so that the event handler in myComponent.parent could be instantiated in that component.

                    Here is the way I ended up doing it:

                    in the component mxml
                    <!-- CUSTOM EVENT METADATA -->
                    <mx:Metadata>
                    [Event (name = "authenticated", type = "flash.events.Event" )]
                    </mx:Metadata>

                    In the method handling the logic

                    private function testValidation(event:ResultEvent):void
                    {if(event.result == true) dispatchEvent( new Event("authenticated") );}

                    in the parent application

                    <local:LoginWindow id="login" authenticated="turnOnPanel(event)" />

                    when using the code sense in Flex Builder, "authenticated" came up as a valid event selection.

                    Thanks again everyone,
                    Jed
                    • 7. Re: Easiest way to dispatch an event from a custom component
                      blueMtnJava Level 1
                      Jed

                      I guess when you said the "easiest way," you weren't kidding. In your case - come to think of it - the EventManager solution i suggested would definitely be an overkill.

                      You need an EventManager when you need to communicate between two components which know nothing about each other. In your case this isn't necessary, since the main app has an instance of the LoginForm.

                      But even for simple cases, I like to centralize my events into one component (such as an EventManager). This is true for the following reasons:

                      a. code reuse - I can easily integrate that EventManager in any other application.
                      b. looser coupling between components - even if the main app did not have an instance of the LoginForm, the two could still communicate.
                      c. team programming - easier for someone else to maintain your event code if it's separated into its own component.