Dispatching a simple event from classB to ClassA

Hi,
I have read at multiple places tutorials/explanations on the EventDispatcher use in AS3 and that confuses me a lot. I would appreciate a lot if somebody could show me in the simple exemple below how I should do to just send a simple message from a ClassB to a Class A. In the exemple below that I made, I have classA that calls classB to send a message that ClassA then gets. Of course, I simplified to the minimum the 2 classes to allow focusing on the problem. Currently, the exemple does NOT work, i.e. the line "trace ("message was received!");" is not executed.
I saw in several exemples on the web that some put the addEventListener on the EventDispatcher object. I do not understand the logic behind this, I would put the addEventListener on the objects that will receive the message.
I wonder also why can't I just put an addEventlistener at the ClassA constructor "addEventListener("hello", receivedHello);" and then send a dispatchEvent from classB. I tried that as well but it does not work.
package {
    import flash.display.MovieClip;
    import flash.events.Event;
    public dynamic class ClassA extends MovieClip{
        public function ClassA(){
            ClassB.getClassB().registerUser(this);
            ClassB.getClassB().sendMessage();
        public function receivedHello(e:Event){
            trace ("message was received!");
package{
    import flash.events.Event;
    import flash.events.EventDispatcher;
    class ClassB {
        public var sender:EventDispatcher;
        // constructor
        public function ClassB() {
            sender= new EventDispatcher();
        // function getClassB() to be sure only one instance of this class is running
        public static function getClassB():ClassB {
            if (ClassB._instance == null) {
                ClassB._instance = new ClassB();
            return ClassB._instance;
        public function registerUser(user:Object){
            user.addEventListener("hello", user.receivedHello);
        public function sendMessage(): void {
            sender.dispatchEvent(new Event("hello"));
Thanks so much in advance for your help
Pieter

package {
    import flash.display.MovieClip;
    public dynamic class ClassA extends MovieClip{
        public function ClassA(){
           addEventListener("customEvent",f);
        function f(e:Event){
            trace("event received");
package{
   import ClassA;
    import flash.events.Event;
    import flash.events.EventDispatcher;
    class ClassB {
        // constructor
        public function ClassB() {
             var a:ClassA = new ClassA();
             a.dispatchEvent(new Event("customEvent"))

Similar Messages

  • Dispatching an ItemClick event from a chart

    I am trying to provide a simple drill down by getting a name
    from a pie slice and then putting the slices contents in a datagrid
    based on that name as a filter.
    I am trying to use an event dispatcher and an event listener,
    but im not exactly sure im doing it right.
    The dispatcher would dispatch when something is clicked, and
    the string item of what is clicked would be passed into the
    remote object. (Not sure how the ItemClick string is passed
    by an event)
    I know i'm a newb with events.... thanks for any input.
    here is the chart component
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Panel xmlns:mx="
    http://www.adobe.com/2006/mxml"
    title="Defect Chart (Status not Closed)" layout="absolute"
    width="100%" height="100%">
    <mx:Script>
    <![CDATA[
    import mx.charts.ChartItem;
    import mx.collections.ArrayCollection;
    //Label function for the Defect Pie Chart
    private function labels(dataItem:Object, field:String
    ,Index:int, dataPercent:Number ):String
    return dataItem.BG_SEVERITY + " " + dataItem.CNT;
    private function ItemClick(name:String):void
    dispatchEvent(new ChartItemEvent.);
    trace("event is dispatched");
    ]]>
    </mx:Script>
    <mx:PieChart id="DefectPie"
    width="100%"
    height="100%"
    showDataTips="true"
    y="40"
    itemClick="{ItemClick(event.hitData.chartItem.item.toString())}"
    >
    <mx:series>
    <mx:PieSeries id="series"
    field="CNT"
    nameField="BG_SEVERITY"
    labelPosition="callout"
    labelFunction="labels"
    >
    This is called in main's init()
    this.addEventListener("name" , ItemClickHandler);
    And this is the handler function:
    private function ItemClickHandler(event:Event):void
    trace(event);
    dataManager.soe_bug_list_detail(event['BG_SEVERITY']);
    }

    JoeADSK,
    This might sound like a bit over-kill but you might go ahead
    and use a seperate EventHandler class and a DTO(Data Transfer
    Object) class to accomplish the event even though you are simply
    sending 1 piece of data.
    Here is an example if you need one:
    ==Event Handler Class==
    package event
    import flash.events.Event;
    import myApp.dto.ChartItemDTO;
    public class ChartClickEvent extends Event
    public var chartName:ChartItemDTO;
    public function ChartClickEvent(chartName:ChartItemDTO,
    type:String)
    super(type);
    this.chartName = chartName;
    override public function clone():Event
    return new ChartClickEvent(chartName, type);
    DTO Class:
    package myApp.dto
    public class ChartItemDTO
    public var name:String;
    public function ChartItemDTO(name:String)
    this.name = name;
    Here is how you use it in your mxml for or whatever:
    import event.ChartClickEvent;
    import myApp.dto.ChartItemDTO;
    DONT FORGET TO ADD THIS EVENT BLOCK:
    <mx:Metadata>
    [Event(name="chartName", type="event.ChartClickEvent")]
    </mx:Metadata>
    HERE IS AN EXAMPLE FUNCTION NON-WORKING===
    private function setChartName(name:String):void
    var chrtName:ChartItemDTO = new ChartItemDTO(name);
    var chrtClickEvent:ChartClickEvent = new
    ChartClickEvent(chrtName, "chartName");
    dispatchEvent(chrtClickEvent);
    Now this is just hacked together quickly not a working model
    but you will get the idea.
    Basically the event must be passed a Data Transfer Object to
    hand off from the Click event.
    Like I said this is over-kill but a good place to start as
    you venture forth in the the Event Handling world in Flex.
    Good luck, hope this helps,
    Kenny

  • Forwarding events from my menubar class to main class

    I'm brand new to swing. I'm trying write an app, and wanted to encapsulate my JToolBar and JMenuBar items, so I made classes to handle each of them. Then from my "main" class I could just call a function and voila.
    However the one obvious problem is that my "main" class doesn't know when JToolBar or JMenuBar items have actions. Those classes each handle their own event listening. I was hoping (probably through magic) that I could then forward that action to the main class somehow.
    The obvious solution would be to expose the individual toolbar JButtons and JMenuItems and call addActionListener(this) on those items from the "main" class. However I'm hoping to avoid having to expose those items, probably just because I'm anal.
    One idea that I've seen but seems kind of not-very-elegant was to create an item to track the state of all things, and pass that item around. Then in my individual actionPerformed() functions I could manipulate that item so that the main class could see those changes.
    I imagine I'll have this same issue when I get into more complicated parts of my would-be application than just the menubar. Any help would be appreciated.

    OK so I can define the new actions in my main class and then in my toolbar/menubar items I just tell them to use those main class Actions? Hopefully I have as somewhat firm a grasp on this as I think I have. I'll try that out now.

  • How to dispatch events from custom AS3 classes to MXML

    Hello,
    I introduce some custom classes inside my SCRIPT tag in MXML.
    These classes should dispatch custom Events (or any events for that
    matter) and the listeners should be defined inside the SCRIPT tag.
    In the custom class I have:
    quote:
    dispatchEvent(new Event("customEvent"));
    And inside the script tag:
    quote:
    addEventListener("customEvent", testListener);
    quote:
    public function testListener(evt:Event):void{
    Alert("Event fired successfully.");
    However, this event is not handled in the listener (the alert
    is not shown). What could be wrong?

    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute" creationComplete="init();">
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    private function init():void
    addEventListener("customEvent", testListener);
    dispatchEvent(new Event("customEvent"));
    private function testListener(evt:Event):void{
    Alert.show("Event fired successfully.");
    Do like this
    Alert is the Class Object. This is not the Function.

  • Dispatch custom event from itemClick handler

    hi,
    I'm trying to dispatch a custom event from my itemClick handler.
    So when I click on an item of my datagrid, I want to send a custom event.
    private function dataGridItemClickHandler( event:ListEvent): void
         dispatchEvent( new myEvent( myEvent.NEW, values[event.columnIndex]["name"]) );
    <mx:DataGrid dataProvider="{values}" itemClick="dataGridItemClickHandler(event)">
    </mx:DataGrid>
    but this code doesn't work.
    Can you help me
    thanks
    best regards

    Please see that you override the function clone() and return the new function.If that is correct.you can call the super() method to initialize your base class.
    If your custom event {myEvent} is in package say: CustomEvent,
    1)import package CustomEvent.myEvent
    2) keep in <mx:metadata>[Event(name="NEW", type="CustomEvent.myEvent")]</mx:metadata>.. name suggest  what type of event you want
    3)Create an itemclick listener and in dataGridItemClickHandler
    private function dataGridItemClickHandler( event:ListEvent): void
         dispatchEvent( new myEvent( ' NEW ', values[event.columnIndex]["name"]) );
    private funcation myEventListener(evt:myEvent):void
    //Put your logic
    4)Use this event by name NEW="myEventListener(event)"  this will behave as event type in the datagrid tag like click, hover and others.
    Hope this helps! Please excuse if anything is logically incorrect.Do point out.Thanks.

  • Simple Event being Displayed Multiple Times

    I have a simple event from the past that is being displayed multiple times. There are no other UIDs that are the same in iCal and no other event has the same SUMMARY name.
    This particular event shows up 9 times. I can also reproduce the result from Automator by searching the specific calendar and looking for events in the date range.
    The event is as follows:
    BEGIN:VCALENDAR
    VERSION:2.0
    PRODID:-//Apple Inc.//iCal 3.0//EN
    CALSCALE:GREGORIAN
    BEGIN:VEVENT
    SEQUENCE:5
    TRANSP:OPAQUE
    UID:EC6F5DBC-9BCC-4007-87F2-4A9C796C8551
    DTSTART:20070330T000000
    DTSTAMP:20071206T205550Z
    SUMMARY:Babysit Paul
    CREATED:20080919T173959Z
    DTEND:20070401T120000
    END:VEVENT
    END:VCALENDAR
    I am not very familiar with the format but it looks pretty straight forward.
    The calendar is being synched via Mobile Me and is shared by another two computers. Not sure why this should be relevant since the entry on the computer and on Mobile Me both show this duplication of the event.
    The reason I was looking at all was because of the hangs in iCal since I set the sync to automatic.
    Any ideas welcome,
    Richard

    Post Author: foghat
    CA Forum: Data Connectivity and SQL
    If all the records you are displaying in your report
    truly are duplicated, you could try check off 'select distinct records'
    from the File --> Report Options menu.  While this may solve the problem for you, it would be worthwhile to determine if you are actually joining your tables correctly.
    likely the records aren't an exact duplicate and the problem is with your join criteria.  To verify this you can:  start by removing table b from the database expert altogether.  does
    that solve your problem of multiple rows?  If it does, you are not joining to table b correctlyIf you still have
    multiple rows, loan_id on its own must not make a record unique.  Is
    loan_id duplicated in either of your tables?  Just because loan_id is a
    primary key does not necessarily mean it is unique - often a record
    will have 2 or more primary keys and only when all primary keys are
    used is the record unique.   If you display all of the columns
    from both tables, you will hopefully see some (maybe just one) columns
    where the value is different between your seemingly duplicate data.
    You may need to join on this value as well.as for the type of join you are using (inner, not enforced) you should be fine. Good luck

  • Dispatching an event from a MovieClip???

    Hello, can somebody tell me if there is a way to dispatch an
    event from a Movieclip?, I tried to dispatch an event from a class
    and all ran ok. But now, if I have a Movieclip on my scenario and I
    want that when it arrive to "x" frame it dispatch an event that
    could be catched by a listener on the _root, what I have to do?
    (without doing use of classes), thanks a lot.

    Try the following. On the first frame of the movieclip place
    the following code.
    // Event Routines //
    var dispatchEvent:Function;
    var addEventListener:Function;
    var removeEventListener:Function;
    mx.events.EventDispatcher.initialize(this);
    Then on the "x" frame of the movieclip, place the following
    code:
    var evt:Object = new Object();
    evt.type = "framereached"; // this can be whatever you wish
    to listen for
    evt.target = this;
    dispatchEvent(evt);
    This is how you would do this in a class and it should work
    just as well if coded directly onto a frame. However, to make this
    more versatile I would place it in a class with a public function,
    for example, name throwEvent(). This public method would then
    execute the above code and could be called from any frame. You
    could even add another item to the evt object that would contain
    the frame the executed the event.
    Tim

  • Dispatch event from the main App file

    Hi,I have one simple question.I know how to dipatch events from the some of the components files to the main App file,but I don't know how to do the opposite?
    I have an HTTPService with id = "getData" in some component file and I want to dispatch an event that will send it getData.send();
    Is this possible,and it if is how?

    It is possible but not a recommended practice.
    Worst case you proxy out methods on your components and call directly:
    maiAPpp.someComponent.doSomething();
    SomeComponent
    doSomething();
        someOtherComponent.doSomething();
    SomeOtherComponent
    doSomething();
        servcie.send();
    My 2 cents are too look into MVC architecture and have the service inside a command which gets treiggered by a controlled which reacts to your event dispatched by the view.
    C

  • Dispatching event from skin

    Can I dispatch an event from the skin and have the hostcomponent listen it?  I have a text input and an info icon in frnt of it,  I want to show the tooltip of the textinput when there is a rollover event on the icon. I wrote a skin with the textinput and icon and in the rollover event on the icon I am dispatching an event and added an event listener to the hostcomponent of the skin. It seems like hostcomponent is not listening the event.
    My skin handles all the animation logic and contains the image and the textinput,and then I am extending the skinnable component class with the two skin parts and controlling the skin states from there. In the rollover event I dispatched an event which host omponent is supposed to catch and do the following:
    myTextInput. tooltip = _toolTip
    _toolTip is in the construcotr of the hostcomponent.
    What is wrong in what I did?  Why is my host component not receiving a event from the skin?

    Thanks for your reply. My code is kinda long and apparently I can't copy paste in this window(not sure why).
    Is there any way to attach the code somehow?

  • Calling Portal event from ABAP class

    Hi Experts,
    I need a following clarificatrion, Please help,
    1. Is it possible to call a webdynpro method from a normal ABAP class?
    2. If no, we need a functionality of a class 'CL_WDR_HTTP_EXT_MIME_HANDLER' having method 'DO_DOMAIN_RELAX_HTML'.
    Is there any alternative method which can be used in ABAP having the same functionality.
    3. Is there any ways with which we can call portal event from ABAP class?
    Thanks,
    Shabir

    >1. Is it possible to call a webdynpro method from a normal ABAP class?
    I wouldn't necessarily recommend this approach. You shouldn't try to trigger events or any of the standard WDDO* methods from outside the WD Component itself.  That said, you can pass the object reference (like the WD_COMP_CONTROLLER object reference or the View Object Reference) into methods of normal classes.  Be careful if you are finding yourself calling a lot of your added methods from outside WD.  This is probably a sign that these methods should be in the Assistance Class or some other Class functioning as a Model Object.
    >2. If no, we need a functionality of a class 'CL_WDR_HTTP_EXT_MIME_HANDLER' having method 'DO_DOMAIN_RELAX_HTML'.
    Is there any alternative method which can be used in ABAP having the same functionality.
    What exactly do you want to do here?  Do you just want to get the relaxation script?  For what purpose?  You should never need to inject the relaxation script into WDA. 
    >3. Is there any ways with which we can call portal event from ABAP class?
    To what purpose.  Do you just want to delegate the triggering of the event that is inside WD Component to be called from a class?  If so you can pass the portal API object reference into a class from the WD Component.  However this only works while running within WD.
    How is this class used?  Are you running in WD?  Are you trying to generate some HTML code that runs in the portal independent of WD?

  • [svn:osmf:] 14474: Adding a 'dispatchInitialChangeEvent' parameter to the ' watch' method in order to allow the initial change event from being dispatched, continued.

    Revision: 14474
    Revision: 14474
    Author:   [email protected]
    Date:     2010-02-28 23:53:31 -0800 (Sun, 28 Feb 2010)
    Log Message:
    Adding a 'dispatchInitialChangeEvent' parameter to the 'watch' method in order to allow the initial change event from being dispatched, continued.
    Modified Paths:
        osmf/trunk/framework/OSMF/org/osmf/metadata/MetadataWatcher.as

    *Feedback*
    "Use the form below to send us your comments. We read all feedback carefully, but please note that we cannot respond to the comments you submit."
    http://www.apple.com/feedback/ipad.html
    We can complain about Apple's business decisions, but these discussions are user to user talk about possible solutions.
    Here are the places to report bugs:
    Get an account at
    http://developer.apple.com/  then submit a bug report to http://bugreporter.apple.com/
    Once on the bugreporter page,
       -- click on New icon
       -- See if you need to attach a log file or log files, clicking on Show instructions for gathering logs.  Scroll down to find the area or application that matches the problem.
       -- etc.

  • [svn:osmf:] 14473: Adding a 'dispatchInitialChangeEvent' parameter to the ' watch' method in order to allow the initial change event from being dispatched.

    Revision: 14473
    Revision: 14473
    Author:   [email protected]
    Date:     2010-02-28 23:45:28 -0800 (Sun, 28 Feb 2010)
    Log Message:
    Adding a 'dispatchInitialChangeEvent' parameter to the 'watch' method in order to allow the initial change event from being dispatched.
    Modified Paths:
        osmf/trunk/framework/OSMF/org/osmf/metadata/MetadataWatcher.as

    Perhaps you're not handling the "EndOfStreamEvent" correctly/at all, and thus not freeing up the socket to listen for the "NewReceiveStreamEvent " after the initial stream has ended...
    ?

  • Dispatching an event from a command

    Hi,
    In one for my commands in the Cairngorm based application I'm working on I need to dispatch a event to amend the view. In my command I'm amending some value objects in a ArrayCollection, which is the data source for a List component in my view. Once I completed my changes to these value objects I'd like to dispatch a event to resort the ArrayCollection and update my view to the new order.
    What is the best approach for dispatching an event in the command?
    Thanks
    Stephen

    Great question - I'm currently sorting out how to do this myself.  I'm new to Cairngorm but have a decent amount of experience with Flex.  Here are my thoughts:
    Cairngorm promotes decoupling of the data model and front controller/commands from the view - which is appropriate for an MVC framework. Data binding supports this seperation (to an extent) and keeps the view up to date with the model in 'real time'.  Data binding does not however provide an intuitive mechanism for reacting to cairngorm event results.  So here a few solutions I've been tossing around:
    1.  Rely on Built in Flex events such as the datagrid's dataChange event to trigger a reaction.
    2.  Create view state variables in the model that, when changed through the front controller / commands, dispatch custom events from within their VO's / setters / ect.
    3.  Dispatch custom events directly from front controller / commands.
    4.  Create custom (or override existing) item renderers that self-transition / tween when changed as a result of data binding.
    I'm sure there are other ways to do what we want, but I'm out of ideas.  Which approach to take very well depends on how strongly you'd like to adhere to the MVC concept.  Commands that dispatch generic events as their messages may or may not be acceptable to you - but they provide a straitforward way to trigger view related reactions without relying on data binding events.  I'd be interested to know if Cairngorm 3 will address this challenge...
    Let me know what you decide on if and when you make a choice!

  • How to dispatch custom events from an item renderer used for Datagrid Column

    Hi,
    I am using an Item Renderer for a Data Grid Column and in that mxml, I am dispatching a custom event with data.
    But the main mxml which has the DataGrid is not able to resolve the event. How can I solve this?
    Thanks

    Hi,
    This is the constructor for Event.
    public function Event(type:String, bubbles:Boolean  = false, cancelable:Boolean  = false)
    When you created your custom event after extending from Event, for the parent container receives the event, the bubbles property must be set to true.
    Please check if you have done so. That should solve the problem. Let me know if it doesn't.
    Nishad

  • Fire event from one class to another.

    I have a Login JFrame class that allows users to enter username and password. I then have another JFrame class which will monitor when someone logs in. I am trying to get the username and password to appear on the monitor login frame text area when the user presses enter on the login frame.
    I can get it ot work by passing the Monitor class into the Login classes constructor but I want to be able to open the classes separately.When I try to open separatley at present I get java.lang.NullPointerException
         at project.LoginGUI.actionPerformed(LoginGUI.java:70) which is referring to the following code:      
    if(listen.equals("OK")){
         GymMonitor.username.setText(username.getText());     
    Both classes are in the same package. What I want to know is how to fire an event from one class to another? when the class you are firing to is constructed separately.
    I hope this question is not too verbose.
    Thanks

    Generally for something like this you would use a listener.
    Your login window is its own entity--it has a user interface, and it gets some information which someone else could ask it for. It could even generate its own events, such as when the user presses "OK". You would first define an interface for anyone who wants to know when someone logs in:
    public interface ILoginListener extends java.util.EventListener
      public void login(LoginEvent event);
    }You would then define the LoginEvent class to contain information like what the user entered for username and password. You could give your login dialog a couple of methods:
      private Vector myListeners = new Vector();
      public void addLoginListener(ILoginListener listener) {
        myListeners.add(listener);
      public void removeLoginListener(ILoginListener listener) {
        myListeners.remove(listener);
      protected void fireLogin(LoginEvent event) {
        for (Iterator it = myListeners.iterator(); it.hasNext(); ) {
          ILoginListener listener = (ILoginListener)it.next();
          listener.login(event);
      }You'd have your login dialog call fireLogin every time the user logged in.
    Then, you could implement ILoginListener in your monitor window:
      public void login(LoginEvent event) {
        // now do something with the event you just got.
      }All the code I put in here is really generic stuff. You'll write this kind of stuff hundreds of times probably during your career. I haven't tested it though.
    Hope this helps. :)

Maybe you are looking for

  • Order quantity is always showing zero in ECC  --- Urgent

    Hi Team, Service order created in CRM Web UI and with service material (Servicing charges) order quantity as u201C1 " at the SM item level defined. Order is getting saved without any errors and replicated well with the amount to the ECC ,  but the Is

  • # of parameters you can pass using AJAX

    I have a weird problem with an AJAX form combined with a CFC.  Just to rule out any possibilities, is there a limit on the number of input fields you can pass to a CFC using AJAX?  I only ask because it appears when the entire form is filled out the

  • SAXParser Exception while viewing the desktop in weblogic portal

    Hi All, I have deployed my portal application on weblogic platform 8.1 SP3. i have created a portal and desktop levaraging the .portal file from my portal application, view desktop throws a SAXParserException as follows. org.xml.sax.SAXParseException

  • Download all tread

    Dear All, I would like to download all the threads and I would like to go through it in my leisure time.  Is it possible to download all questions, related to SD, with all the answers? If possible, please tet us know Thank you

  • Update error 10.6.3

    I keep getting this error everytime I try to update iTunes: The update "iTunes" can't be installed. The update could not be verified. It may have been corrupted during downloading. The update will be downloaded and checked again the next time that So