?
Solved

flex - dispatch event vs event listener

Posted on 2011-10-28
10
Medium Priority
?
967 Views
Last Modified: 2012-05-12
dear experts ,
i want to know what is the difference between using the event dispatch and event listener or call function ??
for example :

when i click save button :
if ( tabBar.selectedItem == "Project Information" )
dispatchEvent(new Event("saveProjectInfo"));

OR

when i click save button :

btn.addEventListener (MouseEvent,Click , callSaveFunction )
if ( tabBar.selectedItem == "Project Information" )
call save function .....

in both cases the results are THE SAME , i wanna know the real difference with examples if possible ....
0
Comment
Question by:mokatell
  • 4
  • 3
  • 3
10 Comments
 
LVL 29

Expert Comment

by:dgofman
ID: 37045479
In most cases better to call a function , but when you need to execute multiple functions at same time or avoidind declaring explicit  references in this case event dispatching is very powerful implementation
0
 

Author Comment

by:mokatell
ID: 37045900
aha ok ... i have a tab bar with five header and eac header has its own data  if i have to call five save functions .and i want to execute them all at the same time ... it is  better use to dispatcher instead of functions ?!!!

if yes ... could it be in the following way :

dispatch ( new Event("abc"));
dispatch ( new Event("xyz"));
dispatch ( new Event("ghj"));
0
 
LVL 2

Expert Comment

by:puzzle-it
ID: 37053512
Most of action done while we use a GUI generate events, for example click a button generate an event, typing on keyboard generates events too and so on, these kind of
A programmer have got the possibility to create new Events customized to its own needs for example checking a form if  it's not filled right an customized event can signal it and this kind of event must be dispatched.
So using addEventListener function the program waits for something is going to happen, dispatchEvent function make something happen.
To garantee that to an event correspond an action one or more listeners must be already attached to the eventDispatcher object is going to dispatch that event, in fact is possible to have more than one eventDispatcher objects into an application.

Now i pass to your effective question, if i understand well you want to synch the execution of 5 functions you can easily do it using just a dispatchEvent(new Event("abc")); paying attention you previously added 5 listener, one for every function, and all them are plugged on the same object, the one you use to dispatch.
This is a pseudo-code of what i mean
ed:EventDispatcher=new EventDispatcher();// this ensure the object is the same for listening and dispatching
ed.addEventListener(YourEvent.String,function1);
ed.addEventListener(YourEvent.String,function2);
ed.addEventListener(YourEvent.String,function3);
ed.addEventListener(YourEvent.String,function4);
ed.addEventListener(YourEvent.String,function5);
ed.dispatch(new YourEvent(YourEvent.String));

Open in new window

I hope this is useful, play a bit with this and i think you will learn easily how to use dispatching and listening.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 29

Expert Comment

by:dgofman
ID: 37054901
I will suggect to create one event listener by some type like

addEventListener("ABC", fucHandler);

now every time when you will dispatch this event type you need just check a target who execute this class

button1.dispatchEvent(new Event("ABC"));
button2.dispatchEvent(new Event("ABC"));
button3.dispatchEvent(new Event("ABC"));
button4.dispatchEvent(new Event("ABC"));

now in the function handler you can get instance id

fucHandler(event:Event):void{
   trace(event.target.id);
}
0
 

Author Comment

by:mokatell
ID: 37057883
thanks for your answers ...
@ puzzle it ... you have said for example if i wanna check  a form is filled or not , in this case i have to make a custom event !!

but i was wondering why cant can i use a regular event listener and check if it filled or not before i save the data ,,,,, this is the part which is confusing me alot ... !!

0
 
LVL 29

Expert Comment

by:dgofman
ID: 37057965
You can but let me give you use case when you should use EventDispatcher implementation
Let believer you have 2 MX Views.
In the first view you have a function
public function saveView1():void
And other
public function saveView2():void
Now in the main Application your implemented  ViewStack and attached these views
<mx:ViewStack id=”vs”>
    <local:View1/>
    <local:View2/>
</mx:ViewStack>
As you may know you can get instance of current view by using vs.selectedChild, but to execute your save function you must check instance of selected view
function onSave():void{
      if(vs.selectedChild is View1){
      View1(vs.selectedChild). saveView1();
     }else if(vs.selectedChild is View2){
         View2(vs.selectedChild). saveView2();
      }
}
Of course by adding more view you must add more conditions to your onSave function
The best way add event listener for each view for example in View1
addEventListener(“SaveEvent”, saveView1);
and in View2  
addEventListener(“SaveEvent”, saveView2);
and add only on line into your save function
function onSave():void{
      vs.selectedChild.dispactEvent(new Event(“SaveEvent”));
}

Now you have nice design and you don’t care how many View(s) you will add in the future your function onSave will never change
0
 
LVL 2

Assisted Solution

by:puzzle-it
puzzle-it earned 2000 total points
ID: 37058462
@mokatell usually when checking a form more operation should be done, for some fields like email field you'd check if it's not empty and you'd check either if a valid email string has been entered.
In some cases just check if a field has been filled is not sufficient, you can handle it using if else or switch case logic inside an handler setted with an addEventListener, but for complex forms, you can imagine, the code will grow rapidly and will get very confusing and hard to maintain.

Generating events, by a side, can mark exactly what's going wrong, by other side generating events decouple your code, an example when a wrong mail is inserted you just signal the user of the mistake nothing more, after 6 month your boss ask you to send him a mail everytime a malformed email is inserted in form, if you are using event dispatching you simply need to write a sendMailFunction and add :
addEventListener(MalFormedMailEvent, sendMailFunction)

Open in new window

it's been easy and fast to add this new feature, after 2 months your boss ask you to send an email to him for every malformed phone number, you need simply to add:
addEventListener(MalFormedPhoneNumberEvent, sendMailFunction)

Open in new window

you are maintaining your code very easy.

Another case of usefulness of dispatching events is when you need to reuse your own code, you can implements all functions checking form fields making them generating events, i.e. checkEmailString(), checkphonenumber() etc. you can use them in all forms you want without any modification of code an you don't have burden reimplementing an if else logic everytime, to handle form checking saving a lot of time.

I hope is clearer now how useful can be event dispatching, it
0
 

Author Comment

by:mokatell
ID: 37074584
fine ..
then can u tell me what is difference between what dgoman said :

addEventListener(“SaveEvent”, saveView1);
and in View2  
addEventListener(“SaveEvent”, saveView2);
and add only on line into your save function
function onSave():void{
      vs.selectedChild.dispactEvent(new Event(“SaveEvent”));
}
 and this one :

save.addEventListener(Event.MouseClick, goandSave);
and in View2  
save.addEventListener(Event.MouseClick ,goandSave);
and add only on line into your save function
function goandSave():void{
 ................... saving instructions !
}

also in this case i can add more conditions and without changing the goandSave function ??
what is confusing me alot there are two approaches and both lead to the same result

guys maybe i am not delivering my questions clearly ! hope this finds you well .
thanks a lot dgoman and puzzle it  , anyway here is what i suggest
0
 
LVL 2

Accepted Solution

by:
puzzle-it earned 2000 total points
ID: 37075264
Right you can add more conditions without changing goand Save function, you say: "what is confusing me alot there are two approaches and both lead to the same result ", yes you are right, i can say you that in computer programming there are a lot of cases where a lot of different approaches lead to the same result, ability of a programmer is in choosing the best one, related to the problem  to solve, but a solution  is not the best always.

Who can say me wich solution is best suited? i can only know it just studying and experiencing.

Event dispatching if used in right way can help you in writing a better maintainable code, and more reusable code but it has got worst performances, but in most of cases this lose of performances is so low that you don't notice it.

The use of an ad hoc function linked to an eventlistener is an immediate solution, for very simple cases you can prefer this solution.

How to choose one solution or the other? you choose case by case, thinking about advantages and disvantages of a solution or another.

For example if you plan to do a library of special visual components, give them possibility to comunicate using eventdispatching is a good option, you can use your components in different project without the need to modify them, instead if you need to enable disable a text field using a button, don't use eventdispatching.

I'm giving you just an example it's not an universal case, but i hope i clarified that it's not so unusual to have more than a way to do a thing in programming, and circumstances can guide us to choose one instead of the others.

Regards
0
 
LVL 29

Expert Comment

by:dgofman
ID: 37115249
I explained what differences between two code styles and provided examples and instead you picked an answer on top my samples  without assigning any points to my answers
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

First things first - Preparation We need all the part for this install and it's much nicer to have them all on hand when you need them so here's what's required. Download Eclipse 3.5 32 bit (I like the Classic flavour) from here. (http://www.e…
Sometimes you know that one object has a specific child in it, but you can't find the child. This happened to me when I was trying to code some actionScript to make a toolbar work with its embedded buttons.  My partner had created the toolbar usi…
In this tutorial viewers will learn how to create a basic shape tween animation in Flash including shape hints for smooth animation Open a new document in Flash: Draw a shape: Select another frame (how long you want the tween to be): Right click and…
The goal of the tutorial is to teach the user how to how to record live broadcast.
Suggested Courses

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question