adding a custom event listener in as3 - actionscript-3

I've done a lot of reading through forum posts and tutorials, but I still can't wrap my brain round events and event listeners. I have a pretty simple example, but I can't get it to work.
I have an arrayCollection of custom objects in a repeater, when one of those objects is clicked, I want a different componenet to display data associated with that object.
Here's what I have, but the listener never responds (the dispatcher seems to be working though, because the new event is created and I can see the trace with the proper output.) I suspect it is because when I call addEvent Listener, I am doing so on the wrong object. My understanding is that the object that will display the object data is the object that should have the event listener, and listen for all events of this nature, but maybe I misunderstood.
My custom event:
public class SelectObjectEvent extends Event
{
public function SelectObjectEvent(customEventString:String, myObject:customObject)
{
super(customEventString, true, false);
trace(customEventString+" "+myObject);
}
}
}
My custom object has the following function which is called on click:
public function selectObject(myObject:customObject):void
{
dispatchEvent(new SelectObjectEvent("OBJECT_SELECTED", customObject));
}
And the component I want to display the selected object has the following constructor:
public function SelectedObjectDisplayClass()
{
addEventListener("OBJECT_SELECTED", this.showObject)
}
public function showObject(event:Event):void
{
trace("Show object: "+event);
}

It's not quite clear where your last two code chunks are, but it looks like you need to be calling addEventListener on the object that extends EventDispatcher.
That is, if your second chunk belongs to a custom object called Clickable, which extends EventDispatcher and calls dispatchEvent() when clicked, then your component should be calling myClickable.addEventListener(...) where myClickable is an instance of Clickable. Does that make sense?
But assuming your 3rd code chunk is not in the same class as the second, it doesn't look like you're doing that. You're adding a listener to the class that owns the third chunk of code, which I gather is not the one that extends EventDispatcher.

Just a quick glance at your code and notice that your dispatchEvent second parameter is the class not the instance of the object. Shouldn't this be myObject?
public function selectObject(myObject:customObject):void
{
dispatchEvent(new SelectObjectEvent("OBJECT_SELECTED", **customObject**));
}

Related

How to dispatch an event with dynamic content in Flex?

I often have the requirement to dispatch a flash.events.Event with soem custom String text, like:
protected function mouseClicked(event:Event) {
//here I'd want to notify anyone interested in the button click,
//and also transfer the name of the button (or whatever) that was clicked - assume some dynamic value
dispatchEvent(new Event("myMouseEvent"), button.name));
}
Of course the above event is invalid. But is there any event that can be used for that type of events? Maybe the TextEvent, but I don't know if I'd be misusing it here.
To include additional data with your events, create a custom event class by extending Event (or any sub-class of Event) and adding your own properties. For example:
class NameEvent extends Event {
public static const NAME_CLICK:String = "nameClick";
public var name:String;
public function NameEvent(type:String, name:String) {
this.name = name;
super(type);
}
}
dispatchEvent(new NameEvent(NameEvent.NAME_CLICK, button.name));
Note that your event type strings ("nameClick" in this example) should be globally unique, otherwise listeners could get them confused with other event types. For example "click" is already expected to be a MouseEvent. I often add prefixes to my custom event types, for example "NameEvent::click".
Another option that does not require creating a custom event is to rely on the expected target to get additional data. For example:
// dispatch a custom event from a Button
dispatchEvent(new Event("myClick"));
// handler for "myClick" events on the button
function myClicked(e:Event):void {
var button:Button = e.target as Button;
trace(button.name);
}
This is not as flexible and also more fragile than using a custom event class, but sometimes a quick easy solution.

Troubles with Custom Events

I've been having lots of trouble with custom events in as3 recently, I've googled a bunch of stuff that doesn't help and used this tutorial to try to figure them out but I'm still confused.
So I set up a new flash fla file to test them and couldn't figure it out, here is what I have:
document as file:
package
{
import flash.events.MouseEvent;
import flash.display.MovieClip;
public class Custom extends MovieClip
{
var intializer:Initializer;
var added:Added;
public function Custom()
{
intializer=new Initializer();
addChild(intializer);
intializer.addEventListener(MouseEvent.CLICK, OnClicker);
addEventListener(CustomEvent.EVENT_CUSTOM, OnCatch);
}
private function OnClicker(event:MouseEvent):void
{
added=new Added();
added.x=300; added.y=300;
addChild(added);
}
private function OnCatch(event:CustomEvent):void
{
trace("hi");
removeChild(added);
}
}
}
event as file:
package
{
import flash.events.Event;
public class CustomEvent extends Event
{
public static const EVENT_CUSTOM="event1";
public function CustomEvent(type)
{
super(type, false, false);
}
}
}
and the movieclips as file:
package
{
import flash.events.MouseEvent;
import flash.display.MovieClip;
public class Added extends MovieClip
{
var addedButton:AddedButton;
public function Added()
{
addedButton=new AddedButton();
addedButton.x=30; addedButton.y=30;
addChild(addedButton);
addedButton.addEventListener(MouseEvent.CLICK, OnClickie);
}
private function OnClickie(event:MouseEvent):void
{
dispatchEvent(new CustomEvent(CustomEvent.EVENT_CUSTOM));
}
}
}
Buttons use an empty class, This gives me this result: (top left corner for first button.)
http://www.fastswf.com/_EfGSoQ
Sorry for so much code, but custom events seem to require a lot of code.
The problem seems to be that you are listening for your custom event in the wrong place. You can address this several ways using event bubbling, the event's capture phase, or by listening for the event on the object that dispatches the event (the event target).
The Flash Event Model follows the W3C event model (used in the DOM/Javascript). When an event is dispatched, it goes through three phases: capture phase, target phase, and bubbling phase. It's described in the above link (in the "Event propagation and phases" section).
For performance reasons (my assumption), the capture and bubbling phases are not enabled by default.
Note you only need to do one of the 3 things below. I suggest using the event target, it's the easiest to understand. The others have their places and can be very useful, but you can do most everything w/the target phase.
How to use the target phase
In your document class remove this line from the constructor:
addEventListener(CustomEvent.EVENT_CUSTOM, OnCatch);
Remove it because we're going to listen for the event coming from the Added object directly (it's the event target). To do that change your code that adds the object in the document class:
private function OnClicker(event:MouseEvent):void
{
added=new Added();
added.x=300; added.y=300;
addChild(added);
added.addEventListener(CustomEvent.EVENT_CUSTOM, OnCatch);
}
How to use the capture phase
In your document class, add an additional parameter when adding the event listener to enable the capture phase:
addEventListener(CustomEvent.EVENT_CUSTOM, OnCatch, true);
This allows any parent of the event target to handle the event, before the target handles it.
How to use the bubbling phase:
To use the bubbling phase, your custom event object needs to "bubble". So you will need to modify the constructor in your custom event class:
public function CustomEvent(type)
{
super(type, true, false);
}
Here I've changed the second parameter in the call to super(), allowing the event to "bubble".
Since the event now bubbles back up the display list, any parent of the event target will also be able to listen for the event after the target has handled it.

Robotlegs - second dispatch does not work with addViewListener

I have a mediator created in Robotlegs, and its related view would dispatch two different kinds of events. When the mediator captures the event, it would just simply dispatch the event. The problem I ran into was that the first event is re-dispatched flawlessly, but the 2nd event was not dispatched.
However, if I manually assign a different handler to the 2nd event, the event is properly captured.
Below is the relevant code:
public class MyMediator extends Mediator
{
[Inject]
public var view:MyView;
public override function onRegister():void
{
super.onRegister();
addViewListener( SomeEventTypeA.COOL_EVENT, dispatch, SomeEventTypeA ); // This event is dispatched correctly
addViewListener( SomeEventTypeB.STUCK, dispatch, SomeEventTypeB ); // This one is not correctly dispatched
//A twist, if I uncomment the following code, the event is captured by its handler
//addViewListener( SomeEventTypeB.STUCK, view_stuck, SomeEventTypeB );
}
private function view_stuck( event:SomeEventTypeB ):void
{
//ah ha, this is called correctly if the above relevant line is uncommented
}
}
Found the cause:
The event needs to have a proper clone method in order to be re-dispatched correctly. See related link:
http://knowledge.robotlegs.org/kb/application-architecture/why-doesnt-my-event-trigger-the-command-it-is-mapped-to

How to access the variable "abc" in the following code structure

1) First of all I don't wanna use CustomEvent class. Some solution I am looking without using CustomEvent.
2) One of the solution can be having abc variable in ClassA. And then dispatching directly via ClassA ( rathar than saying classB.dispatchEvent() ). But still looking if there is some better solution than this.
//Frame1 code :
import flash.events.Event;
var classA:ClassA = new ClassA() ;
classA.addEventListener("hello", hello);
classA.init();
function hello(e:Event)
{
trace(e.currentTarget.abc); //<<<< NEVER EXECUTED
}
//classA
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class ClassA extends MovieClip
{
var classB:ClassB ;
public function ClassA()
{
classB = new ClassB();
}
public function init()
{
classB.dispatchEvent( new Event("hello"));
}
}
}
//classB
package
{
import flash.display.MovieClip;
public class ClassB extends MovieClip
{
public var abc:Number =123;
public function ClassB()
{
}
}
}
You are missing a couple key concepts before you can get your example to work. First you are dispatching the event on an instance of ClassB, however you are listening on an instance of ClassA. So, they have to be related in some way, in order for event to be properly orchestrated when it gets dispatched. One way to do that is to use event bubbling. One caveat to that is that native event bubbling only really works for DisplayObjects, but both of your classes inherit from MovieClip so thats not a big deal.
So the first thing, you have to understand how bubbling events work. A simplified explanation is that events start at the top of the display hierarchy and capture down the display tree towards the element, they are finally dispatched on the target, then they turn around and bubble back out in the opposite direction.
This means that your instance of ClassB has to be a child of ClassA. So the first thing you'll have to change is in your ClassA constructor:
public function ClassA()
{
classB = new ClassB();
addChild(classB);
}
Next, when you dispatch the event, you'll need to explictly say that its a bubbling event, otherwise it'll be triggered on the target, and neither capture nor bubble through the display stack.
public function init()
{
classB.dispatchEvent( new Event("hello", true));
}
The second argument of true sets the event to a bubbling event.
Finally you'll need to change your handler. Right now, it's using e.currentTarget, which isn't going to be what you expect in this case (usually it is, thought).
You have to understand the difference between e.target and e.currentTarget. e.target is the actual target of the event, independent of how its bubbling or capturing. e.currentTarget on the other hand is the element which is presently handling the event. So in your case e.currentTarget is an instance of ClassA (the instance that the event handler is actually attached to) and e.target is an instance of ClassB (the instance that the event was dispatched on). During the event lifecycle, e.currentTarget will change as the event moves around, but e.target should always be the same.
In this case, you want to reference the actual target of the event, not the element that is currently processing the event. So you need to change your handler to:
function hello(e:Event)
{
trace(e.target.abc);
}
And then it should work. You can find a working example here that encapsulates the changes I've described.
If these classes weren't DisplayObjects then you would have to take a different approach -- either by using a signal pattern or to manually listen for an retrigger the event inside ClassA.
First of all you are adding an event listener to classA but your classA init method is asking classB to dispatch an event and this is the reason why your code does not get executed. If you want to catch the hello event you should be doing something like
public function init()
{
this.dispatchEvent( new Event("hello"));
}
Or you should be registering the listener on classB (which is not in scope so no code suggestion).
In ActionScript the best approach to transfer information is to use custom events so my suggestion is to re evaluate your decision on custom events.

Flex event handler not working

I have created a custom event in flex 3.5. But the handler is not invoked. How to solve this or what is the way to debug this problem?
The Event class:
package com.saneef.worldlanguages.events
{
import flash.events.Event;
public class LanguageEvent extends Event
{
public static const LANGUAGE_SELECTED:String = "LanguageSelected";
public function LanguageEvent(type:String,languageid:String)
{
super(type);
this.langid = languageid;
trace("LanguageEvent: " + this.langid);
}
public var langid:String;
override public function clone():Event {
return new LanguageEvent(type, langid);
}
}
}
Dispatching:
private function functionOne():void
{
try{
dispatchEvent(new LanguageEvent(LanguageEvent.LANGUAGE_SELECTED,"STR"));
}
catch(e:Error)
{
trace(e.message);
}
}
In the Main application class, EventListener:
protected function application1_initializeHandler(event:FlexEvent):void
{
this.addEventListener(LanguageEvent.LANGUAGE_SELECTED,
application1_LanguageSelectionHandler);
}
The event handler function:
public function application1_LanguageSelectionHandler(event:LanguageEvent):void
{
trace("application1_LanguageSelectionHandler: " + event.langid);
populate_countrya3id_languages(event.langid);
}
Your code looks fine. Since I can't see the full source, here are my two thoughts on what may be going on:
Are you sure your addEventListener call is done before you dispatch the event? Add some trace to make sure the application1_initializeHandler prints before functionOne does.
Is your functionOne call in another different component than your main application? If so, you'll need to set your custom event's bubbles attribute to true in your event's super call.
public function LanguageEvent(type:String,languageid:String,bubbles:Boolean=True)
{
super(type, bubbles);
this.langid = languageid;
trace("LanguageEvent: " + this.langid);
}
See the flash.events.Event docs for the constructor call. Also, here's a quote about the bubbles argument explained here:
The bubbles property
An event is said to bubble if its
event object participates in the
bubbling phase of the event flow,
which means that the event object is
passed from the target node back
through its ancestors until it reaches
the Stage. The Event.bubbles property
stores a Boolean value that indicates
whether the event object participates
in the bubbling phase. Because all
events that bubble also participate in
the capture and target phases, any
event that bubbles participates in all
three of the event flow phases. If the
value is true, the event object
participates in all three phases. If
the value is false, the event object
does not participate in the bubbling
phase.
Based on your source code, it looks like you've seen the "Dispatching Custom Events" in the flex docs, but I'll link to it anyways for future/easy reference: http://livedocs.adobe.com/flex/3/html/help.html?content=createevents_3.html.
Also, check out http://www.adnandoric.com/2008/12/29/understanding-the-flex-event-propagation/ for a high-level overview of the event propagation system to try to get a better understanding of what's going on while developing.
Edit:
Based on your comments I'm guessing your functionOne call is in a separate class and your "main" application has an instance of this class. If that's so you'll want to attach your event listener on that instance and delegate it to your main's application1_LanguageSelectionHandler function... Like so:
protected function application1_initializeHandler(event:FlexEvent):void
{
this.theInstanceThatHoldsYourFunctionOne.addEventListener(LanguageEvent.LANGUAGE_SELECTED,
application1_LanguageSelectionHandler);
}