How do I attach a global event listener? - actionscript-3

I am working on an AIR application:
The main window is like a dashboard. With the menu bar, I can open other windows with dashboard details. When I close these, I'd like to refresh the main window.
I tried to use an event listener, but the result is not good. If I open detail windows directly from the main window, I know how to add an event listener - and it works - but I don't know how to do it, if the detail window is opening from the menubar!
Thanks for helping me.

A Singleton is what you are looking for. Just put an event dispatcher inside and you will be able to listen from everywhere in the application.
A Singleton is like having a unique instance of an object in memory, so anyone modifying a variable inside that object ( or sending events throught ) will be modified for everyone.
Here is an example of code on how to use it.
http://life.neophi.com/danielr/2006/10/singleton_pattern_in_as3.html
Note: Singletons are powerful and dangerous at the same time, there is a lot of talk about how to use them, please read a little more about that if you are considering building a big project.
Hope it helps!

The issue is that you're performing business logic from a View. Don't do this. Instead, dispatch an event from each menu rather than directly opening the window from within it. Listen for those events at a higher level, and then you can either directly listen to the new windows you have opened, or you can create a base window Class that exposes a variable of type IEventDispatcher. If you populate that variable with the same event dispatcher, what you wind up with is called an "event bus," and you can listen on that for events.
This architecture requires a little more thought than using a Singleton, but it avoids the tight coupling and other issues you'll run into by introducing one into your project.

You can listen to an object (EventDispatcher) directly by adding an event listener to it, or if the dispatcher object is on the displaylist, such as a Sprite, you could listen at the stage level with the capture parameter set to true.
But the main caveat is that the dispatcher must be on stage for you to catch this event.
Your main window listens to stage (with capture = true):
stage.addEventListener("MY_CUSTOM_EVENT", handle_custom_event, true);
private function handle_custom_event(e:Event):void
{
var sub_window:Object = e.target;
// do something to your sub_window
}
Your sub window can dispatch events like this:
dispatchEvent(new Event("MY_CUSTOM_EVENT"));
But (ab)using the stage as a message passing infrastructure for custom events in this way is a little messy. You could consider a more formal message passing architecture if you really want this kind of communication. Even a static MessageBus class would at least quickly help you identify where you use this in your codebase. Either way, you'll have to be careful about references and memory leaks.

Related

Is better create a single object Event instead of always create another?

Usually when dispatching an Event (or custom Event) I use this:
function fireEvent():void {
dispatchEvent(new Event(Event.COMPLETE));
}
Is better use a single object to dispatch an event every time? Can I do this?
var myEvent:Event = new Event(Event.COMPLETE);
function fireEvent():void {
dispatchEvent(myEvent);
}
It would be a way better (eg create event pools) if it works. Unfortunately AS3 does some internal magic with event object during event flow which makes objects only one time usable (Sorry, by some reason I can't find proof quickly).
You can easily get confirmation by dispatching event second time, your listeners will not be triggered (may be it's true only for bubbling feature, not remember exactly), so you have to create a new instance of event object for every dispatchEvent call.
It doesn't worth it even if pooling works, I presume. Creating event objects isn't expensive in astionscript, adding event listeners is. You'd better put this effort on managing listeners and handlers which could easily become the performance buttleneck.

Firing a KeyDown event in WinRT

Is there a way to fire a custom KeyUp/KeyDown event on the CoreWindow?
For example, take the following event:http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.core.corewindow.keyup.aspx.
My application already uses CoreWindow::KeyUp and CoreWindow::KeyDown to handle events. I am trying to test that the correct delegates are being attached and thus called when an event happens.
Note that I can't call the delegate function directly since it will not test the fact that the delegate is attached to the event.
I am looking for an answer similar to https://stackoverflow.com/a/3977396/756356.
I doubt that's possible because it sounds like something possibly interfering with the sandbox concept of modern apps. You could maybe insert some layer between the CoreWindow and your handlers and bubble the events through that layer to make is possible to raise your proxy events. I would recommend against that though since that just adds code you don't need.

Why use custom events instead of direct method calling?

I'm new to programming and I've been checking a lot of game coding tutorials. I've noticed that on most of them they use custom events to trigger methods instead of calling a method directly.
What's the reasoning behind this practice? Why aren't they just calling the method?
For example:
We have two objects: A and B. A has method A.methodA() that B needs to use when X condition is triggered.
Why implement:
B dispatches an event to A that tells A to run A.methodA()
Instead of:
B uses A.methodA()
The main reason is separation of interests. When using events, class A doesn't need to know about the existence of class B (and vice versa).
Some benefits to this are:
Much easier unit testing (you can test Class A without class B)
Less chance of breaking your code when you change class A or B
Less references to other classes in your code, which reduces the potential for memory leaks
Cleaner code
More flexible/reusable code (a bunch of other classes could all listen/respond to the event without any additional code in the your dispatcher)
Typically in bigger applications using events will help abstract everything. When you have 15+ classes and they're all ditpatching events to a controller, it's a lot easier to figure out what's going on than reading through all different parts of the code to trace functions. Using callbacks begins to create spaghetti code.
However, direct function calls are going to be executed faster than events.
Personally, I use custom events simply for the ease of use. I can have one class dispatch an event when something happens (say an animation finishes or an error occurs in a download) and any number of other classes run any number of other functions based on that event. In addition, I code for reusability. The goal of each class is complete independence so that it can run in any project without needing other packages. So rather than have one class call a method of another class, I dispatch an event from the first class that the second class listens for and then run that method. Then when I need that first class for another project, I can just copy/paste it without having to modify it and without losing any functionality.
EDIT:
Also, it's worth noting that sometimes people do what you describe to get around having to pass in event arguments.
Say you have a button on the stage and you need to be able to click it, but you also need to be able to manually call that method. Some people don't realize you can pass in a null event and have only the single method. Or you can set it as a null default argument, see below:
private function onClickHandler( e:MouseEvent = null ):void{
//as long as you never reference "e" within this method, this method can be used both for MouseEvent listeners and manually calling it elsewhere in the code
}
That technique can help avoid having an event handler that only calls another method and nothing else. At this point in my programming, every single AS3 event handler I write sets the event argument to null by default. It just makes things easier later on.
You might want to read this.
And also note using the callback method allows you to pass parameters to it directly and not via a custom event model.
I built my own, very simplified, events dispatcher system. AS Event model is very powerful, but in 99% of situations you don't need that power. A simple callback with parameters fired as an event is more than enough. You can still retain the versatility from an event model, but don't need to write too many lines of code for, let's say, a simple button.
I can setup a simple event like this:
Buttonizer.autoButton(_buttQuit, this, "onPress");
public function onPressQuit(c:Sprite) {
// Execution goes here
}
You can build your own event model, it will make life simpler, and your code much more concise.

What exactly this method do ? addActionListener

What exactly will this addActionListener Do.....we we call button.addActionListener(this) what will happen
It basically adds this (the current object) to a list of objects that will be notified when the component has an action performed on it, such as a button being pressed.
It's a way of registering your interest in what is happening to the component and is useful in that you don't have to keep polling a component to check its status.
Your object (or class, really) simply implements the interface methods for listening (such as actionPerformed) and that method will be called for each event that happens.
The Java tutorials have a large variety of different articles on the various listeners that you're likely to use.

What do you think about NResponder?

I was on the point of start using AS3 Signals for my new project because Native Events has a bad reputation, and then I found this:
http://code.google.com/p/nineveh-responder/
But I couldn't find more information (in addition to official docs and tuts).
What do you think about NResponder?
OT: I can't create the tag "NResponder" in this question because is new :(
NResponder goes above and beyond the call of duty. It is soo easy to use and learn. The real difference maker is its NResponder.remove(action,function,target) method.
It has the ability to remove all event listeners that fall under the parameters provided. In one call, you can remove all listeners associated to one object(target), any listeners associated to a certain function, listeners that respond to a certain event like MouseEvent.CLICK, or any combination of these parameters.