tutorials flash events_as3_01

AS3 Event

Actionscript 3 proposes a new events system which eliminates the old AsBroadcaster in favour of a model close to that proposed by W3C with its adaptation of DOM Event Model Level3.

Let us quickly see how to use this new event-driven system. There are already many articles on this subject in the community (see the links at the end of this article) but in my opinion it is also useful that I too study the subject. Maybe my article could teach you something new (I hope!).

If you already use events a little, it will seem apparent to you that an event-driven system is based upon 3 object types:

  • Event dispatchers
  • Events
  • Listeners

These three object types are essential in order to create communication between objects. It is on this principal that Adobe have defined their model with the following elements:

1 - flash.events.IEventDispatcher is the interface which is going to implement the events dispatcher.

2 - flash.events.EventDispatcher is the principal class of the AS3 framework which implements the IEventDispatcher interface. In looking closer at the Flex2 documentation we quickly realise that the classes MovieClip, TextField, etc use quite a particular inheritance which ascends towards the EventDispatcher class. I again advise you to read Iteratif’s article on this subject:: the new architecture of the AS3 framework.

The EventDispatcher class is therefore the principal class to create an event diffuser by inheritance or composition … it’s up to you ;) This class possesses all of the necessary methods to register a listener for a given event type, to diffuse events to listeners, etc.

3 - The listeners are the only ones to depart from W3C’s model. Adobe has in effect decided to use the functions instead of a class which implements an EventListener interface (a class which contains a method handleEvent(ev:Event)).

This choice is in my opinion a strategically and maturely considered one by Adobe. I acknowledge that this disturbs me a little compared to my usual usage in VEGAS which itself uses an implementation of the EventListener interface as proposed by W3C.

At the end of the day, the most important in all of this, if you are accustomed to using events with the AsBroadcaster class or the EventDispatcher class of the MX AS2 components package, is to understand that the ultimate goal of the propagation of an event remains to call a function which will launch certain instructions when necessary.

As a result this implementation makes it possible to concentrate on the event and that which emits the event and a little less on the listener which in the AS3 model becomes a simple function (object of the Function type) which you just need to target.

It now remains to study a small example in detail which will quickly illustrate the use of this model :)

I decided to put forward some new and very useful events available in AS3 which in my opinion are going to very quickly find their place in the development of your applications. Let us look a little closer at the Event.ACTIVATE, Event.DEACTIVATE events.

package
{
 
	import flash.display.Sprite;
 
	import flash.events.Event ;
 
	public class TestEvents extends Sprite
	{
 
		// ----o Constructor
 
		public function TestEvents()
		{
 
			addEventListener(Event.ACTIVATE, onActivate) ;
			addEventListener(Event.DEACTIVATE, onDeactivate) ;
 
		}
 
		// ----o Public Methods
 
		public function onActivate(e:Event):void
		{
			trace("> " + e) ;
		}
 
		public function onDeactivate(e:Event):void
		{
			trace("> " + e) ;			
		}
 
	}
 
}

After a few tests on these events you will realise that they make it possible to know if the currently running animation takes the focus of your OS or if on the contrary it loses it. These 2 events can, in a practical sense, be used for certain types of games for example to pause an animation if the user changes window, for example to prevent his boss seeing what he’s playing during working hours lol … You can also imagine creating a site containing music and cutting it at the opening of a popup which will launch some video, it will be possible when the user returns to the main animation to automatically restart the music after a simple click in the visual area of the animation.

We see with this example that if an object uses the event-driven model of the AS3 framework, that it is enough to use the addEventListener method to record a type of event given a function which will again serve as the listener during the emission of this event in the following code. On the contrary, to unsubscribe a listener, it suffices to use the removeListener method by calling it in the same manner as the addEventListener method used previously.

Note By reading the reference of AS3 language or my example above, you can see that the type of event in the addEventListener and removeListener methods are String type character strings. Adobe uses constants (Event.ACTIVATE, EVENT.DEACTIVATE, etc…) for all its events to store these strings and in the end this method allows the developer to concentrate on nothing else but the event which he wants to use. I advise you to quickly accustom yourself with handling events-related constants because in the second reading of the code it will be much easier for you to avoid errors (typos and such like).

To use the event-driven system by means of clips, buttons, all classes native to the framework already put in place is a good thing, but now it would maybe be interesting for you to create your own events and your own events diffusers. For that nothing could be easier, let us look at a simple example:

package
{
 
	import flash.display.Sprite;
 
        public class TestEvents extends Sprite
	{
 
		// ----o Constructor
 
		public function TestEvents()
		{
 
			var u:User = new User("eka") ;
 
			u.addEventListener(UserEvent.SPEAK, onSpeak) ;
 
			u.speak("Hello World") ;
 
			u.removeEventListener(UserEvent.SPEAK, onSpeak) ;
 
			u.speak("I Love AS3 !") ;
 
		}
 
		// ----o Public Methods
 
		public function onSpeak(e:UserEvent):void
		{
			trace("> " + e.getName() + " : " + e) ;
		}
 
	}
 
}
 
import flash.events.Event;
import flash.events.EventDispatcher;
 
class UserEvent extends Event
{
 
	// ----o Constructor
 
	public function UserEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
	{
		super(type, bubbles, cancelable) ;
	}
 
	// ----o Constants
 
	static public const SPEAK:String = "onSpeak" ;
 
	// ----o Public Methods
 
	public function getName():String
	{
		return currentTarget.getName() ;
	}
 
}
 
class User extends EventDispatcher
{
 
	// ----o Constructor
 
	public function User( name:String="empty" )
	{
		_sName = name ;
	}
 
	// ----o Public Methods
 
	public function getName():String
	{
		return _sName ;
	}
 
	public function speak( message:String ):void
	{
 
		trace("> User : " + _sName + " , speak : " + message) ; 
 
		var e:UserEvent = new UserEvent( UserEvent.SPEAK ) ;
 
		dispatchEvent( e ) ;
 
	}
 
	// ----o Private Properties
 
	private var _sName:String ;
 
}

I think that this example is simple enough and illustrates well the creation of a specific event and its propagation via the dispatchEvent method. I am using the EventDispatcher class here with inherits from the User class, but it is sometimes preferable to use this class by composition.

I personally am quite happy with this event-driven system in spite of some minor problems relating to tools which I implemented in VEGAS and which are lacking in AS3. For example it is impossible in the current framework position to create a master listener or to even create a master event transmitter. I am therefore thinking about the installation of tools which would avoid these missing elements but I do not know if I will manage to extend, as I would wish, to all of the functionalities put in place in VEGAS while keeping AS3 methods? Another final point to note would be that I find the management of events actions very limited (Broadcasting Event, Capturing, etc) uniquely on the DisplayObject type objects! I really do not know if it is possible to extend this limitation to the level of native classes and to obtain a “universal broadcasting”? More to follow on this subject…

I will pass over everything here that relates precisely to the management of events actions (Broadcasting Event, Capturing Event, etc) and I am going to direct you while writing a complete tutorial on this subject towards the article of Liguorien: AS3 - events. There you can see that certain functionalities could be very useful for those who will go a little further than a simple broadcasted event when one clicks on a button :)

In all of my next tutorials I will completely use AS3 events, and if you need any further explanations on certain points please do not hesitate to ask me in the comments of my blog :)

By EKAMELEON - ALCARAZ Marc (2006). You can find this tutorial and comments on the subject on my blog.








Adobe Training center


Mediabox Training Centre © 2000 - 2008 All rights reserved.
Adobe Authorized Training Centre. State convention under number 25 14 02167 14.
Mediabox : SARL au capital de 62.000€ - Activity number: 25 14 02167 14 - SIRET : 493 716 468 00027
MEDIABOX, 102 Avenue des Champs Elysées, 75008 PARIS - Tel. +33(0)2.31.91.96.89 - Fax. +33(0)2.72.68.56.42