Custom Event not being heard - actionscript-3

I'm working on a mobile AIR project using Flash Builder 4.6. I'm dispatching a custom Event but it is never being heard. I've checked similar questions but cannot find an answer which solves it for me. In my main mxml file I add the listener in the addedToStage event:
[EDIT] adding the listener to the userStatus instance. Still not working.
<s:ViewNavigatorApplication
...
private var userStatus:UserStatus;
protected function addedToStageHandler(event:Event):void
{
userStatus = new UserStatus();
userStatus.addEventListener(CustomEvent.CREDENTIALS_READY, credentialsReadyHandler);
The CustomEvent class:
public class CustomEvent extends Event
{
public static const CREDENTIALS_READY:String = "credentialsReady";
public function CustomEvent(customEventString:String){
super(customEventString, true, false);
}
}
The class which dispatches the CustomEvent after a successful service call:
public class UserStatus extends EventDispatcher
{
...
//event handler
private function userStatusLoaded(e:Event):void
{
var json:Object = JSON.parse(paidUserLoader.data.toString());
if(json.success == "true")
{
trace("UserStatus::this is a paid user!");
dispatchEvent(new CustomEvent(CustomEvent.CREDENTIALS_READY));
}
I can see the trace statement in the console, so I know the code is getting there. But the listener in the s:ViewNavigatorApplication class never fires.
Can anyone see why?
Thanks.

Any custom class event has to override the clone() method. This method is automatically called internally but if it's not present (overrided) then only direct dispatch can work but events cannot traverse a hierarchy.
EDIT: nvm, there's no reason for your ViewNavigatorApplication to actually catch that event since UserStatus is not a DisplayObject. You are confused about how event are dispatched and are supposed to work. Only the UserStatus itself can catch the event it is dispatching. No other object can. In the case of a display list event propagate but for all non displayobject they need to catch their own dispatch.
EDIT: Answering comment:
There's somewhere a reference of the UserStatus instance, it might be in the ViewNavigatorApplication or not, if it is then:
myuserstatus.addEventListener(CustomEvent.CREDENTIALS_READY, credentialsReadyHandler);
would work. If it's not there then you need to pass along the information from whether class having the reference to UserStatus to the ViewNavigatorApplication. This can be done by redispatching the event (this is where you need to override clone()).
The instance of someotherclass has a reference to userstatus and does listen for the event. When the event fires the someotherclass instance catches and redispatches it. The ViewNavigatorApplication listen for that event directly or via the someotherclass instance reference and finally catches the event.
EDIT: responding to new edits
Let's fix your custom event class. By default you set bubbling to true but only DisplayObject can bubble so it should be set to capture (false)
super(customEventString, false, false);
That should fix it I bet.

Related

AS3: Best way to register event listeners

My question today is about the way we can register an event listener.
Let's say we have a Group element and inside it a custom Handler element. We want the Handler element to do something when Group triggers a custom event. Now, what is the best way to do it?
var group:Group = new Group();
var handler:Handler = new Handler();
group.addElement(handler);
Now, what is the best way to register the event listener?
1. Go on and do it from the file where we initialized the objects
group.addEventListener("CustomEvent", handler.handlerFunction);
2. Register the event listener from the Handler's class:
parent.addEventListener("CustomEvent", handlerFunction);
3. Any other way?
You can let Group class instance dispatch custom event directly on Handler class instance. Handler class would have an internal listener registered for example in constructor.
public function Handler() {
addEventListener("CustomEvent", handlerFunction);
}
Group class would dispatch event following way:
handler.dispatchEvent(new CustomEvent());

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.

Why isn't dispatchEvent firing?

okay so here is my problem in my main project I'm trying to fire an event using dispatchEvent I've made a simple test class to test this and yet it still isn't working...
Here is the test class
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main() {
stage.addEventListener("pOver", rake);
dispatchEvent(new Event("pOver"));
}
public function rake(e:Event):void {
trace("working");
}
}
Why isn't it firing? or why is the listener not capturing that event?
You are dispatching the event on the Main, which is a child of Stage. If you want to specifically dispatch an event on the Stage then use:
stage.dispatchEvent(new Event("pOver"));
Now you may be wondering, "If it's a child, then my event handler should still be getting triggered!"
Well, yes and no.
Lets take a look at a simple diagram of the event life-cycle:
First, the event that you are dispatching is not a bubbling Event. Examining the Event constructor, its signature looks like this:
public function Event(type:String, bubbles:Boolean = false, cancelable:Boolean = false)
Notice that the second argument is by default false, which means this event does not perform the bubbling part of the event life-cycle.
Second, you have attached the event dispatcher on the bubbling side of the event life-cycle. If you look at the signature for .addEventListener() it looks like this:
public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Notice the third argument. Which is by default false again. This means that you are attaching on the "bubbling" side of the event.
This means that this event is getting to the targeted element, the instance of Main, and then stopping and not going anywhere else.
TL;DR: So what does that all mean?
So to trigger your event handler, and not change where the event gets dispatched, you need to change your event that you are triggering to:
this.dispatchEvent(new Event("pOver", true)); // this event will bubble
Then your event handler, since it is a child, will be triggered by this event.
Conversely, I think that non-bubbling events will also progress through the capturing side of the event life-cycle so you could also change your event listener to attach to that side of the event as well.
stage.addEventListener("pOver", rake, true); // attach to a capturing side
I believe that event will always flow through the capturing phase, even if they are marked as not bubbling. But I could be wrong on that. I just can't remember if "non-bubbling" events skip both capturing and bubbling phases and just trigger the target event phase and I don't have time to check it right now.
Edit
So, I wrote up a quick test on wonderfl:
package {
import flash.events.Event;
import flash.display.Sprite;
public class FlashTest extends Sprite {
private var debug:TextField;
public function FlashTest() {
stage.addEventListener("Foo", bubbleFooHandler);
stage.addEventListener("Foo", captureFooHandler, true);
trace("Ready");
trace("---------------");
trace("Trying a non-bubbling event");
this.dispatchEvent(new Event("Foo"));
trace("---------------");
trace("Trying a bubbling event");
this.dispatchEvent(new Event("Foo", true));
}
private function captureFooHandler(e:Event):void {
trace("Triggered \"Foo\" from capturing phase\n");
}
private function bubbleFooHandler(e:Event):void {
trace("Triggered \"Foo\" from bubbling phase");
}
}
}
The output from this is
Ready
---------------
Trying a non-bubbling event
Triggered "Foo" from capturing phase
---------------
Trying a bubbling event
Triggered "Foo" from capturing phase
Triggered "Foo" from bubbling phase
Notice that events will always progress through the capturing phase. However, if they are not marked as a "bubbling event", see before, they will descent through the tree they stop when they arrive at target of the event (the EventDispatcher the event was dispatched on).
Bubbling events, on the other hand, will turn around and head back up the tree.
Hopefully, this clears things up.
First of all, you are listening to stage events. This means that as long as stage is not dispatching any Events you will not get any callbacks.
try
stage.dispatchEvent(new Event("pOver"));

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);
}