2 Replies Latest reply on Mar 1, 2007 5:54 PM by webjoseph

    Could some one explain to me how Custom Events work?

    xyco45 Level 1
      I tried looking in the live docs and still it confused me, so then I went searching on the net and found this very lovely tutorial http://www.tink.ws/blog/custom-events-in-as-30-dont-forget-to-override-the-clone-method/ but still it confused me. The part I am puzzled on the most is that when you create like a event that listens for when your mouse clicks something is setup like addEventListener(MouseEvent.CLICK, eventHandler) etc, etc. And when a mouse is clicked the event is triggered! but if the CLICK constant is just a a string value what is going on behind the scenes that tells it (lets say Flex is talking -->) "okay he/she specified the 'CLICK' constant so I guess this means I will make this event happen only when the mouse clicks on that particular object" and same with MouseEvent.DOUBLE_CLICK how does it know to trigger this event only when the mouse double clicks on a item. I want to make my own custom events that trigger a particular event based on what a object does, but I just don't understand how to set it up and implement it.
        • 1. Re: Could some one explain to me how Custom Events work?
          buabco Level 1

          The hole concept of event dispatcher is that events get fired all the time, if there is someone listening to the event or not. In your own example, the CLICK event gets fired each time someone clicks on the object.

          When you add an event listener basically what you are doing is adding a function to a queue of functions that get executed each time a specific event is fired. This is very important to keep in mind from the object disposal point of view, since for the garbage collector to actually kill an object all reference to it must be eliminated, and this include the reference in this queue for the listening function.

          The reason that an event name is simply a String is so you can actually define any event you might like. Still is good practice to define constants for your events names since it will avoid a lot of errors when writing code.

          Now to fire an event all you need to do is dispatch a specific event using the "dispatchEvent" function. This is what happens each time you click on an object, the dispatchEvent(new Event(Event.CLICK))) function is called.

          If you are using custom events it's a good idea to extend the Event class so you can add some extra information to the event, for example, in the MouseEvent the x and y coordinates of the mouse are added. To dispatch a custom event all you do is call the event dispatcher with the custom event:

          dispatchEvent(new CustomEventClass(Some Data));
          • 2. Re: Could some one explain to me how Custom Events work?
            Consider this resource as well if you haven't already found it: