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.
Related
I have an event class which extends the normal events class so I can pass parameters and have custom events.
I have a message event which I use to display a message to the user, I send an event to trigger this message from many places in my project.
I now need to give the user an option in this message and access the answer in the original class which sent the event that triggered the message.
My solution is to pass a function as a parameter to the event listener, then on click the function in my original class is called.
Is this a good approach?
My other solution was to create more events to handle the various options, but I may end up with many types of events.
This is not a traditional delegation of concern. If the original class cares about an event, it should listen for it and react to it. If you wanted to extend "event" it would traditionally be to have it carry more data (or more descriptive data), not to have it carry a function closure.
I'm using redux and es6. I want to dispatch an action before components will mount. The problem is that with redux newest syntaxis componentWillMount doesn't exists any more. So... where should i dispatch this action.
My case: I have a component that needs user's info (such as name, for example). I need to get the user's name before that component mounts.
thanks,
Connect your component to a field in your state, let's call it "name". When the component renders, make sure it checks if name is not empty; if it is then it renders it, if not then it renders nothing.
In the componentDidMount, fire your dispatch as normal - this in turn will reduce and end up changing the value of "name" in your state. This will cause a re-render and will then show properly.
componentWillMount only exists server side, so it is usually not the best idea to dispatch actions from it, as if you just had your client side code, they wouldn't work.
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.
I am starting developing with Symfony2 framework and I like to use the Eventdispatcher. Now I have three questions I could find an answer with google yet.
Where I place the dispatcher so it is accessable from everywhere in
tha app?
How I can configure customevents? Should I place all in one file or
one for each bunble?
How much effort is it to configure it with annotations, i.e
#Event("some.event")? Is that possible?
General
I might suggest the Symfony 2 documentation on the EventDispatcher as a good starting point, assuming that you mean you wish to provide custom events rather than a custom event dispatcher.
Symfony2 Internals - The Event Dispatcher
Location of Events
In terms of location, an 'Event' folder within the appropriate bundle is a good choice. It is likely that the actual dispatching of the event will take place only within the bundle context, whereas listeners may reside elsewhere. This is however a separate topic and of minimal relevance as they simply subscribe to the event's string-name (e.g., 'store.order' to borrow the documentation's example) and only require knowledge of the Event's interface/type.
So you might have an Event called 'Foo' within the 'Bar' bundle in 'Zap' namespace:
namespace Zap\Bar\Event;
use Symfony\Component\EventDispatcher\Event;
class FooEvent extends Event
{
// ...
}
When you then come to dispatch an event from within your bundle, you might choose to use the event identifier 'zap.bar.foo', and of course you can then register listeners from elsewhere to be notified on this identifier as you see fit.
Accessing the Event Dispatcher
Where you wish to access the primary EventDispatcher instance, acquire access to the Dependency Injection Container and retrieve the 'event_dispatcher' service. A simple approach is to have your class extend 'ContainerAware' and then retrieve the dispatcher with
$dispatcher = $this->container->get('event_dispatcher');
To answer your first question:
Where I place the dispatcher so it is accessable from everywhere in tha app?
Actually, there is already preconfigured event dispatcher service accessible, as #jstephenson pointed out, by calling $dispatcher = $this->container->get('event_dispatcher'); so you don't have to create your own instance anywhere.
However, if you need your own event dispatcher, you can simply configure it in your services configuration file (i.e. services.xml) of your bundle like this:
<service id="my_dispatcher" class="Symfony\Component\EventDispatcher\EventDispatcher" />
You can of course use your own dispatcher class as long as it implements EventDispatcherInterface.
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.