events (listeners/handlers: mouse, keyboard, timer) flash actionscript 3.0 introduction to thomas...

16
Events Events (Listeners/Handlers: Mouse, (Listeners/Handlers: Mouse, keyboard, timer) keyboard, timer) Flash ActionScript Flash ActionScript 3.0 3.0 Introduction to Introduction to Thomas Lövgren, Flash developer [email protected]

Upload: winfred-sanders

Post on 22-Dec-2015

233 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

EventsEvents(Listeners/Handlers: Mouse, keyboard, (Listeners/Handlers: Mouse, keyboard,

timer)timer)

Flash ActionScript Flash ActionScript 3.03.0

Introduction toIntroduction to

Thomas Lövgren, Flash developer

[email protected]

Page 2: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

Event and common tasksEvent and common tasks Why events? And why is it so important? Why events? And why is it so important?

The answer is simple: We can’t have an interactive The answer is simple: We can’t have an interactive application without detecting user inputs!application without detecting user inputs!

We need events for many different tasks, here’s a We need events for many different tasks, here’s a few examples: few examples: Buttons: Press, release, rollOver, rollOut etcButtons: Press, release, rollOver, rollOut etc Keyboard: Keypress, keyRelease etcKeyboard: Keypress, keyRelease etc TextInput: TextInput: Change, TextInput, Enter Change, TextInput, Enter Timer: Start and stop timer eventsTimer: Start and stop timer events Loading data (Event complete) Loading data (Event complete) Animations (Frame Event)Animations (Frame Event)

Page 3: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

Event handlingEvent handling For Event Handling in AS3, there are tree For Event Handling in AS3, there are tree

important important stepssteps we want to identify: we want to identify:

1. 1. The event sourceThe event source: Which object is the event is : Which object is the event is going to happen to? For instance, which button will going to happen to? For instance, which button will be clicked etcbe clicked etc

2. 2. The eventThe event: What’s going to happen, the thing that : What’s going to happen, the thing that we want to respond to? we want to respond to?

3. 3. The responseThe response: What step(s) should be performed : What step(s) should be performed when the event happens?when the event happens?

Page 4: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

EventDispatcherEventDispatcher TheThe EventDispatcher class is the base class for all EventDispatcher class is the base class for all

classes that dispatch events classes that dispatch events Event Dispatchers Event Dispatchers are objects that dispatch are objects that dispatch

events to objects that are registered as listenersevents to objects that are registered as listeners An event system consists of 3 main entities: Event An event system consists of 3 main entities: Event

Dispatchers, Listeners, and Event ObjectsDispatchers, Listeners, and Event Objects EventDispatcher class methodsEventDispatcher class methods

addEventListener();addEventListener(); removeEventListener();removeEventListener(); dispatchEvent();dispatchEvent(); hasEventListener();hasEventListener(); willTrigger();willTrigger();

Page 5: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

Event ObjectsEvent Objects Let's recall that when an event happens, Flash will Let's recall that when an event happens, Flash will

create an object that will be sent to the registered create an object that will be sent to the registered function function

This object contains at least the following This object contains at least the following information: information: Type : A string indicating the type of event Type : A string indicating the type of event Target : The instance that sent the event (i.e. a Target : The instance that sent the event (i.e. a

reference to it) Since target refers to an object you reference to it) Since target refers to an object you then can also extract information about the target, then can also extract information about the target, e.g. its label (if it has one)e.g. its label (if it has one)

To get this working properly we need to set up our To get this working properly we need to set up our Listener Listener and and Handler/FunctionHandler/Function……

Page 6: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

Event Listener and HandlerEvent Listener and Handler For each event (user action or something else), we For each event (user action or something else), we

need to register a an need to register a an event listener event listener and an and an event event handler/functionhandler/function

Let’s look at the basic syntax of this:Let’s look at the basic syntax of this:

//add eventlistener to object, specify the event, call the function//add eventlistener to object, specify the event, call the functioneventTarget.addEventListener(EventClass.EVENT_NAME, eventHandler); eventTarget.addEventListener(EventClass.EVENT_NAME, eventHandler);

//the event handler/function//the event handler/functionfunction eventHandler(eventObject:EventType){function eventHandler(eventObject:EventType){

//actions performed in response to the event go here//actions performed in response to the event go here}}

Page 7: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

MouseEvent MouseEvent The The MouseEvent class MouseEvent class is useful for activities like: is useful for activities like:

Mouse clicks, mouse navigation, drag and drop, roll Mouse clicks, mouse navigation, drag and drop, roll over/roll out, drawing by mouse etcover/roll out, drawing by mouse etc

In this example we use an event called CLICK for In this example we use an event called CLICK for detection of a mouse click detection of a mouse click

//add eventlistener to object, specify the event, call the function//add eventlistener to object, specify the event, call the functionmy_button.addEventListener(MouseEvent.CLICK, clickHandler);my_button.addEventListener(MouseEvent.CLICK, clickHandler);

//handler/function that proceeds the action //handler/function that proceeds the action

function clickHandler(event:MouseEvent){function clickHandler(event:MouseEvent){

trace(”Button click: Testing Listener and Handler!”);trace(”Button click: Testing Listener and Handler!”);

}}

Note! Note! The argument in the handler/function contains The argument in the handler/function contains information about the eventinformation about the event

Page 8: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

Event Listener Event Listener ParametersParameters

The The addEventListener() addEventListener() method method can have 5 parameters, can have 5 parameters, the first two are compulsory:the first two are compulsory:

//params: eventName, function, capturePhase, priority, useWeakReference//params: eventName, function, capturePhase, priority, useWeakReferenceeventTargeteventTarget.addEventListener(.addEventListener(EventClass.EVENT_NAMEEventClass.EVENT_NAME, , eventHandlereventHandler, false, 0, true);, false, 0, true);

eventName: eventName: EventClass and Name of event (EventClass and Name of event (compulsory)compulsory) function: function: Function/event handler call (Function/event handler call (compulsory)compulsory) useCapture (boolean)useCapture (boolean): When this parameter is set to true, we'll : When this parameter is set to true, we'll

listen to the event in the capture phase. By default this parameter listen to the event in the capture phase. By default this parameter is set to falseis set to false

priority (int)priority (int): This is to make sure that a certain event listener has : This is to make sure that a certain event listener has a higher priority than a different event listenera higher priority than a different event listener

useWeakReference (boolean)useWeakReference (boolean): When this parameter is set to true : When this parameter is set to true it will create a weak link between the object and event listener. A it will create a weak link between the object and event listener. A weak reference is not counted by the Garbage Collector (reference weak reference is not counted by the Garbage Collector (reference will be removed next GC sweep). Recommended that we use truewill be removed next GC sweep). Recommended that we use true

Page 9: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

KeyboardEvent KeyboardEvent The The KeyboardEventKeyboardEvent class is useful for activities class is useful for activities

like: Keyboard navigation, keyPress, tabbing etclike: Keyboard navigation, keyPress, tabbing etc In this example we use the an event called In this example we use the an event called

KEY_DOWN for detection of a keyPressKEY_DOWN for detection of a keyPress

//add eventlistener to object, specify the event, call the function//add eventlistener to object, specify the event, call the functionstage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);

//handler/function that proceeds the action //handler/function that proceeds the action

function keyDownHandler(event:KeyboardEvent){ function keyDownHandler(event:KeyboardEvent){

trace("You just pressed a key!"); trace("You just pressed a key!");

} }

Page 10: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

Common EventsCommon Events Some of the most common events for Mouse and Some of the most common events for Mouse and

Keyboard (with a migration guide between AS2 and Keyboard (with a migration guide between AS2 and AS3):AS3):

Page 11: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

removeEventListenerremoveEventListener It’s a good idea to remove listeners that we know It’s a good idea to remove listeners that we know

will no longer be needed. This could easily be done will no longer be needed. This could easily be done by the by the removeEventListener methodremoveEventListener method

The The removeEventListener removeEventListener method requires two method requires two parameters: The event and the function specified parameters: The event and the function specified when the listener was createdwhen the listener was created

For example like thisFor example like this::

//remove the listener from button//remove the listener from button

my_button.removeEventListener(MouseEvent.CLICK, clickHandler);my_button.removeEventListener(MouseEvent.CLICK, clickHandler);

Page 12: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

Event ArgumentsEvent Arguments(Multiple Events, One Listener (Multiple Events, One Listener

Function)Function) Every handler function has one argument: Every handler function has one argument: The event The event

argumentargument. This argument contains data about the event and . This argument contains data about the event and the event dispatcherthe event dispatcher

The most common The most common event arguments event arguments are: type, target & are: type, target & currentTargetcurrentTarget

In this example we can use In this example we can use event.type event.type to catch the mouse to catch the mouse eventsevents

//add listener to stage for mouse event//add listener to stage for mouse eventstage.addEventListener(MouseEvent.MOUSE_DOWN, handler); stage.addEventListener(MouseEvent.MOUSE_DOWN, handler); stage.addEventListener(MouseEvent.MOUSE_UP, handler); stage.addEventListener(MouseEvent.MOUSE_UP, handler);

//event function/handler//event function/handlerfunction handler(event:MouseEvent){ function handler(event:MouseEvent){ if(event.type == "mouseDown"){ if(event.type == "mouseDown"){ trace("Down"); trace("Down"); }else{ }else{ trace("Up"); trace("Up"); } }

}}

Page 13: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

TextEventTextEvent Let’s look at an example were we use the Let’s look at an example were we use the

TextEvent TextEvent class for detecting typing in a text field: class for detecting typing in a text field: entry_txtentry_txt is an input text field, and is an input text field, and output_txt output_txt is a is a dynamic text fielddynamic text field

//add listerner to the input textfield//add listerner to the input textfield

entry_txt.addEventListener(TextEvent.TEXT_INPUT, updateOutput);entry_txt.addEventListener(TextEvent.TEXT_INPUT, updateOutput);

//function that picks out the pressed keys//function that picks out the pressed keys

function updateOutput(event:TextEvent):void{ function updateOutput(event:TextEvent):void{

var pressedKey:String = event.text; var pressedKey:String = event.text;

output_txt.text = "You typed: " + pressedKey; output_txt.text = "You typed: " + pressedKey;

} }

Page 14: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

MouseEventMouseEvent(Random number) (Random number)

This example generates a random number between This example generates a random number between 0-100 on every mouse click, the numbers will appear 0-100 on every mouse click, the numbers will appear in a dynamic text fieldin a dynamic text field

//add eventlistener to object, specify the event, call the function//add eventlistener to object, specify the event, call the functionrnd_button.addEventListener(MouseEvent.MOUSE_DOWN, randomNumber);rnd_button.addEventListener(MouseEvent.MOUSE_DOWN, randomNumber);

//handler/function that proceeds the action //handler/function that proceeds the action

function randomNumber(event:MouseEvent){function randomNumber(event:MouseEvent){

rnd = Math.random() * 100; rnd = Math.random() * 100; //generate a random number between 0-100//generate a random number between 0-100

random_txt.text = String(rnd); random_txt.text = String(rnd); //cast number to string, output//cast number to string, output

}}

Page 15: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

Timer EventTimer Event The Timer class is very useful if we want to fire an The Timer class is very useful if we want to fire an

event within an interval (with a specific delay)event within an interval (with a specific delay) The Timer Object can have two parameters (delay, The Timer Object can have two parameters (delay,

repeatCount)repeatCount)

delay is compulsorydelay is compulsory The start method starts the timer (there’s also a stop The start method starts the timer (there’s also a stop

method)method)

//example of using the timer, delay and repeatCount//example of using the timer, delay and repeatCount

var timer:Timer = new Timer(1000, 5); var timer:Timer = new Timer(1000, 5); //1000 miliseconds = 1 sec//1000 miliseconds = 1 sec

//add listener and call the onTimer function/handler//add listener and call the onTimer function/handler

timer.addEventListener(TimerEvent.TIMER, onTimer); timer.addEventListener(TimerEvent.TIMER, onTimer);

timer.start(); timer.start(); //start timer//start timer

function onTimer(event:TimerEvent):void{ function onTimer(event:TimerEvent):void{ //function/handler//function/handler

trace(”Timer ticking!”); trace(”Timer ticking!”); //output//output

}}

Page 16: Events (Listeners/Handlers: Mouse, keyboard, timer) Flash ActionScript 3.0 Introduction to Thomas Lövgren, Flash developer thomas.lovgren@humlab.umu.se

Frame EventFrame Event The Frame event is very useful for all kinds of The Frame event is very useful for all kinds of

animations, it’s basically a frame loop - the event animations, it’s basically a frame loop - the event occurs at the rate of the frame rateoccurs at the rate of the frame rate

Let’s say out movie has a frame rate of 30 fps, then Let’s say out movie has a frame rate of 30 fps, then the event will be called 30 times a secondthe event will be called 30 times a second

//add the listener to the movieClip, event class, function call //add the listener to the movieClip, event class, function call

my_mc.addEventListener(Event.ENTER_FRAME, enterFrameHandler); my_mc.addEventListener(Event.ENTER_FRAME, enterFrameHandler);

//function/handler that animates a movieClip//function/handler that animates a movieClip

function enterFrameHandler(event:Event){ function enterFrameHandler(event:Event){

my_mc.x += 5; my_mc.x += 5; //move the clip 5 pixels right every enterframe //move the clip 5 pixels right every enterframe

}}

Note! Note! More of this in the Animation/Motion lecture…More of this in the Animation/Motion lecture…