Which object in hierarchy should add event listener?

Hello all,
I'm quite new to the whole OOP thing, and one of the things I keep wondering about is this:
Which class should listen for events if the choice is between a contained class or a containing class?
For example:
An instance of Game holds an instance of Board which holds an array of instances of fields.
This might be a scenario for a simple board game, I guess (In my case I am working on Reversi).
A player should click a field to place a piece on it. I could let the Field class listen for the click event,
but when a player places a piece, other pieces might have to flip, so an object at a higher level should handle this (board / game / maybe another object).
So in order to make sure this happens, I could let the field object listen for the event and than tell the higher-level-object to do his thing, or I could
let the higher-level-object add an event listener on the field object, and than both flip the nescesary pieces as well as tell the field to add a piece on itself.
Could anyone explain which and why either solution (or maybe a third on) is better?
Thanks for your time!

qdudu wrote:
Hello all,
I'm quite new to the whole OOP thing, and one of the things I keep wondering about is this:
Which class should listen for events if the choice is between a contained class or a containing class?The class that can respond to the events should implement the Listener.
For example:
An instance of Game holds an instance of Board which holds an array of instances of fields.
This might be a scenario for a simple board game, I guess (In my case I am working on Reversi).
A player should click a field to place a piece on it. I could let the Field class listen for the click event,
but when a player places a piece, other pieces might have to flip, so an object at a higher level should handle this (board / game / maybe another object).Sounds like Board would be a good choice, then.
So in order to make sure this happens, I could let the field object listen for the event and than tell the higher-level-object to do his thing, or I could
let the higher-level-object add an event listener on the field object, and than both flip the nescesary pieces as well as tell the field to add a piece on itself.Sounds like the field object can't do much except forward the event to the real handler. In that case I'd vote for the higher-level-object as the listener.
Could anyone explain which and why either solution (or maybe a third on) is better?In this case it could be either one. Try both and see. But based on the little you've posted here I'd vote for the higher-level-object, the Board.
%

Similar Messages

  • How to add event listener?

    i want to add event listener when i click on a button in mxml, the event listener should be added in the action script file, how to do this?
    can anyone help? urgent!!!

    Hi Lakshmi,
    You can do this just put all the script in the mxml block in seperate AS file as shown below... Observe that I have included an AS file named Script.as and removed the script block form mxml and moved to this Script.as file. Place the Script.as file in your src folder ....
    // Main mxml file....
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="onCreationComplete()">
        <mx:Script source="Script.as"/>
    <mx:TextArea id="textArea" width="300" height="100" />
    <mx:Button id="myButton" label="Click ME"/>
    </mx:Application>
    //Script.as file
    import mx.controls.Alert;
                private function onCreationComplete():void
                 myButton.addEventListener(MouseEvent.CLICK, onButtonClick);
                private function onButtonClick(event:MouseEvent):void
                 Alert.show("Button is Clicked");
    Thanks,
    Bhasker

  • Which dc and sc should add in build time form sld when integration uwl

    hi
    i have to create a webdynpro to show info from uwl, like follow
    IUWLService uwlService=(IUWLService)PortalRuntime.getRuntimeResources().getService(IUWLService.ALIAS_KEY);
    but i don't know which dc and sc i should add in build time form sld and use it.
    i try add UWLJWF from sld, and ?
    i develop with nwce ehp1
    thank you

    1) tc/je/security/api
    2) tc/je/usermanagement/api
    from ENGFACADE.
    3) tc/kmc/bc.uwl/api
    from UWLJWF

  • Add event listener to HTTPService call

    Hi – I am using a HTTP service within my flex
    application.
    My HTTPServeice is connecting to an XML file:
    <mx:HTTPService
    id="myResults"
    url="
    http://localhost/myResults.xml"
    resultFormat="e4x"
    result="resultHandler(event)" />
    the data within the XML file is constantly changing (the
    structure remains the same, but the actual data within the
    structure of the XML changes), therefore I am refreshing my
    HTTPService results every 5 seconds:
    [Bindable]
    public var myDataFeed:XML;
    private function initApp():void
    var timedProcess:uint = setInterval(refreshResults, 5000);
    private function refreshResults():void
    myResults.send();
    private function resultHandler(event:ResultEvent):void
    myDataFeed = event.result as XML;
    My problem is that sometimes the XML file needs longer than 5
    seconds to load / refresh the data (as it is quite heavy)
    etc… therefore I want to implement some sort of event
    listener on the HTTPService to let the application know when the
    results have been refreshed so I can restrict / the 5 second
    refresh taking place until the previos refresh is complete
    etc…
    is this possible – to set an event listener to a
    HTTPService to know when it has completed refreshing results from
    an XML file???
    Thanks,
    Jon.

    result="resultHandler(event)" <--- is already an event
    listener.
    btw if you have a live XML you might want to consider xml
    socket connection so that server will push data to client .(lot
    more efficient)

  • Add Event Listener for the deletion

    How can we add an event listner on the deletion of an item in the document?

    As far as I know, InDesign DOM doesn't have such event, but Rorohiko's Active Page Item Developer (APID) Toolkit has it:
    subjectDelete — Sent when one of the observed page items is about to be deleted.

  • How to add event listener to datagrid ROW

    I need to know if it is possible to have the datagrid rows execute a state change.
    For example: I have a datagrid populated with various items, when one row is selected I want it to change the state of a part of the canvas it is in.
    How is this possible? I can not give the row an id so I would not be able to say "when row is selected change state" because there is no way to tell what row is selected.
    Help please. Thanks.

    See Flex 4 and MXDataGridItemRenderer.

  • Help regarding event flow/event listening best practices

    Hi, I'm making a flash memory card game to learn more about
    to actionscript.
    I have:
    - a main class that loads on start. This class instantiates
    a:
    - CardLoader class that imports graphical assets and uses
    these to create all my cards:
    - Card class that represents individual card. Can dispatch
    CardEvent when clicked:
    - CardEvent contains info on the Card that dispatched it,
    such as the cards ID number and the ID of it's matching card.
    What I want to do is to have another object to act as a game
    logic handler.
    Example:
    - Card 1 was clicked, dispatches CardEvent that ends up with
    the LogicHandler.
    - Card 2 was clicked and also dispatches event.
    LogicHandler compares these two cards and does the
    appropriate thing depending on they being a match or not.
    Now, the big questions is, how do I get this event to the
    LogicHandler?
    My custom CardEvent has it's bubbles property set to true.
    So, I can manage to get such an event all the way back to my main
    class, in this order: CardEvent > Card > CardLoader >
    Main.
    The problem arises when I want to have my LogicHandler class
    created by Main. When my CardEvent bubbles back, it does not go
    through this LogicHandler since it is not part of the event flow on
    it's way back.
    Questions: How do I, following the best possible programming
    practises, send the event the way I want it to go?
    I can only think of one solution myself, being that inside my
    Main method I set up an eventlistener that listens for this event
    and passes it on downwards, in this case to the LogicHandler. Sure,
    it's only a few lines of code in the main method, but what if you
    have 50 different events in a larger project that needs the same
    treatment?
    Your main method will be a mess by then!
    How would you do it?

    Ok let me see if I get this straight:
    In my example, I would have to pass a reference of the
    LogicHandler to my Card class.
    In my Card class, I have something like:
    logicHandler.addDispatcher(this);
    this being the Card of course.
    Inside LogicHandler class I have the addDispatcher method
    that calls the addEventListener method.
    So far so good?
    The addDispatcher method adds an eventlistener to the Card
    object, from what I can tell. But it does it inside the
    LogicHandler, thus the method that is called by the
    addEventListener can be inside the LogicHandler?
    To put it in other words, what's confusing me is that the
    Listener object adds an EventListener to the dispatching object.
    Logically for me the listener should add a listener to itself?
    The way I first did it in my Card class was:
    testevent = new CardEvent(CardEvent.CLICK);
    dispatchEvent(testevent);
    And then set up the EventListener in the object that I wanted
    to receive the event.
    I'm sorry I don't understand this, despite your obviously
    good explanations (I think I understand a lot more now, just not
    the best approach). I will look into the callback functions, sounds
    a lot interesting as well

  • Unable to add the Listener class in project .

    Hi friends ,
    I'm using deploytool of Sun's AppServer 8.2.
    I'm not abel to add the Eventlistener class in the project.
    In the Help Menu the given following discription to Add the Event Listener call
    Web Application WAR File -> Event Listeners tabbed pane
         1. Click Add to add an event listener to the Event Listener Classes list.
         Locate any event listener classes contained in this WAR file in the drop-down list in the Event Listener Classes      pane.
         (note:There is no any drop-down list in in the Event Listener Classes pane.)
    2. If the event listener class is not in the list, in the General tab, click Edit and to go to the Edit Contents      dialog box where the event listener class can be added to the contents of the WAR file. Upon return the event      listener class will be in the pull-down list.
              (note:But the listener class is present in General tab ,WEB-INF->classes->listeners(In the Contents of the           General tab.))
    How could i resolved this , i mean how to add Event Listener Classes in project ?
    (Same problem while adding error page and filter classes which are also present in the General tab)
    Regards,
    Sachin Warang.

    I suggest using NetBeans IDE 5.5, which integrates easily with various appservers, including Sun Java System Application Server.
    -cheng

  • BeforeSave event listener reverting doc to unsaved [AS, CS5]

    Hi,
    I've got an AppleScript, which is triggered by a beforeSave event listener.  This script makes some modifications to the active document, and then the save proceeds.  The problem I'm encountering is that, after the save, the document appears as saved momentarily, but then immediately reverts back to unsaved.  This is evident by an asterisk disappearing and reappearing next to the document name in the document window's title bar.  If I comment out the document modification code, the save works as expected. 
    It seems like maybe the save is continuing while the script is still in progress, and this is why the document reverts to unsaved.  However, shouldn't the beforeSave event take place before the save occurs, and not proceed until the script has finished executing?
    Things I've checked and/or tried…
    * I've checked to see if somehow my script is being triggered a second time after the save is complete.  It is not.
    * I've tried having my script save the document on completion, but this fails because the database is busy.
    * I've tested with beforeSaveAs, and it encounters the same problem.
    * I've tested on multiple machines.  What's weird is that it occurs on some, and not on others.  So, it's not consistent.
    * I have seen the problem in Mac OS X 10.5.x and 10.6.x.  I have not tested it in 10.7.x yet.
    * I have seen the problem with CS5, but have not yet encountered it with 5.5.
    Anyone have any thoughts or suggestions?
    Thanks,
    -Ben

    Thanks for the ideas regarding beforeInvoke, Ben.  I will try to check that out.  In my situation, here's essentially how my script is working...
    BeforeSave is invoked.
    Script makes a change to the document, which should be captured in the saved file.
    Document saves.
    Document appears saved for a moment, and then appears unsaved (asterisk in the document title).
    My biggest problem is that this behavior isn't consistent.  I have dozens of users, all running the same script, and the problem only occurs with certain users and at random times. I can move a problematic document from a user's machine to a different machine, and the problem doesn't occur there.  It's very difficult to troubleshoot because I can't reproduce it consistently.

  • URGENT : EVENT Listener Problem

    Hi All,
    Thanks for your time. I am facing a Small issue with Event
    dispatcher and Add Event listener. Well i will explain the problem.
    I am having one MovieClip named BUTTON_SET and i gave
    "ButtonSet.as" as linkage Class.
    Inside that BUTTON_SET i am having some Buttons and they are
    also having "UIButton.as" as linkage class
    UIButton Dispatching press and release events, But unable to
    capture it using ButtonSet Class. Here with i have attached the
    Code and i gave the Source URL Too.
    upto my Knowledge : UIButton class is not initiated When the
    ButtonSet is ready to addListener.
    Please Help me to fix this.
    if i don't find a solution i need to change all my class
    structures.
    CLICK HERE FOR SOURCE
    CODE

    According to your Code, When you are calling the InitHandler
    Functionction the Buttons may/may not be Initiated. So use the
    Enterframe to check whether its loaded or not.
    Write down this in the ButtonSet to replace the init Handler
    Call.
    this.onEnterFrame = Delegate.create(this, initHandler);
    inside the initHandler remove the function This will help you
    if you are not using any Enterframe for any other manipulation)
    delete this.onEnterFrame;

  • Android Cache Event Listener

    Hello guys,
    I'm working in a project with HTML5 and Cache Manifest for Android or IOS device. The files was cached nicely for both devices, but, when I add event listener to the cache application on android device, it doesn't callback and the cache status stay 0.
    My code example is: http://gist.github.com/felipehaack/c858e416e7187763739d
    I really appreciate some help

    I've sent this to our test team and they're taking a peek. I know we tested it in the past and it worked.
    Neil

  • Add event function

    hello;
    i have function that retun value and want to use it with add event listener
    function sayname (naame:String)
      trace("yourname is  " +naame )
    sayname("mohamed")
    if i use button to call this function  i try
    but1_btn.addEventListener(MouseEvent.CLICK,sayname("mohamed"))
    but i doesnt work i guess because it take var( e:Event)
    how can i do this

    If you are going to hardcode the name anyways then you can just assign it to a variable...
    var naame:String = "mohamed";
    but1_btn.addEventListener(MouseEvent.CLICK, sayname);
    function sayname (evt:MouseEvent):void 
      trace("yourname is  " +naame );

  • How to know which leaf node i click and how to add a listener to each node?

    hi! hello to all members, i have a problem i know how to create a listener, but i dont know how to add a listener to each leaf node. here is the scenario i want to do, i have a JTree where theres a topic that you can select on each leaf node, so when the user click the specific topic it will open another JFrame,which i dont know how to do it also, that its! the next problem will be how do i know which leaf node i select, so that i can open a right topic before the JFrame will open?please, i am very need this to solve quickly as possible. thanks again to all members.

    What you have to do is to add a mouse listener on your JTree. Try something like this:
    tree.addMouseListener(new java.awt.event.MouseAdapter() {
             public void mouseReleased(MouseEvent e) {
                tree_mouseReleased(e);
    private void tree_mouseReleased(MouseEvent e) {
          TreePath selPath = tree.getSelectionPath();
          // Check If the click is the Right Click
          if (e.isPopupTrigger() == true) {
          // This is your right Click
           else {
                     // This is your Left Click
    }Your other problem: Set the userObject on nodes and on left click compare it with your object, if it matches, display the appropriate file. Alternatively, if your nodes are unique, you can match the names to open the file.
    Hope this Helps
    Regard
    Raheel

  • How to add exiting event listener in javascript

    I am trying to figure out how to add an event listener in javascript for the exiting event when the red x is clicked on a Windows window (top right corner).
    I found this among adobe documentation, but it does not work:
    var app = air.NativeApplication.nativeApplication;
    app.addEventListener(air.Event.EXITING, closeHandler);
    function closeHandler(event) {
      alert("Goodbye.");
    And yes I have the AIRAliases.js included.
    Thanks

    The code posted above is from page 10 of the "HTML Developer’s Guide for ADOBE AIR (prerelease updated 11/16/2009)".
    I am actually exiting the program because I only have one window open and I click on the red x in the top right corner to shut it down... in theory, the example above provided by Adobe, should interrupt the exit sequence by displaying an alert box amd then shut the program down.
    Here's the excerpt from the manual...
    unload events (for body and frameset objects)
    Adobe AIR 1.0 and later
    In the top-level frameset or body tag of a window (including the main window of the application), do not use the unload event to respond to the window (or application) being closed. Instead, use exiting event of the NativeApplication object (to detect when an application is closing). Or use the closing event of the NativeWindow object (to detect when a window is closing). For example, the following JavaScript code displays a message ("Goodbye.") when the user closes the application:
    var app = air.NativeApplication.nativeApplication;
    app.addEventListener(air.Event.EXITING, closeHandler);
    function closeHandler(event)
    alert("Goodbye.");
    However, scripts can successfully respond to the unload event caused by navigation of a frame, iframe, or top-level window content.
    Note: These limitations may be removed in a future version of Adobe AIR.

  • My iPhone 5s was just updated recently to 7.1.1. Now my calendar information got deleted and I can't add any events to my calendar. The   button in the top right corner should be orange but it's grey and it won't let me add events when I try to click onit

    I'm trying to add events to my calendar after they got deleted and it won't let me because the + is grey when it should be orange. Does anyone know what to do?

    You are on Windows 2000, you do not have a "Firefox" button, and should consider yourself to be fortunate in that you still have menus and don't have to do anything to get the menus back instead of the "Firefox" button. (The same applies to Windows XP users).
    Use the "File" menu to get to Import. You are not on Windows 7 or Vista, and don't have to put up with the nonsense added for Aero.
    If you want the "Firefox" button you can get it with View -> toolbars -> (uncheck) Menu Bar. The menu bar and the "Firefox" button were supposed to be mutually exclusive (which is impossible in some cases without being incompatible).
    Once you are using the "Firefox" button ...
    Use the "Alt" key to view the menu bar (temporarily) containing File, Edit, View, History, Bookmarks, Tools, and Help. On Windows 7 and Vista, the menu bar was hidden by default in Firefox 4 and above. These menu items are more or less available under the "Firefox" button which has the most used of the built-in Firefox menu items available in a different format.
    To get back to having menus again. "Firefox" button -> Options (second column) -> (check) Menu Bar
    You can make '''Firefox 7.0.1''' look like Firefox 3.6.*, see numbered '''items 1-10''' in the following topic [http://dmcritchie.mvps.org/firefox/firefox-problems.htm#fx4interface Fix Firefox 4.0 toolbar user interface, problems (Make Firefox 4.0 thru 8.0, look like 3.6)]. ''Whether or not you make changes, you should be aware of what has changed and what you have to do to use changed or missing features.''
    * http://dmcritchie.mvps.org/firefox/firefox-problems.htm#fx4interface

Maybe you are looking for

  • How do I install ExportPDF on a new computer?

    I purchased Adobe Exportpdf on October 21.  Since then my laptop has crashed and I had to buy a new laptop,  How do I install the adobe software on my computer?  My order number is AD014478128.  Thank you

  • Hide or Remove the Navigation "Heading" in ONET.XML

    Hello guys, I am creating a custom template (onet.xml) where I would like to Hide/Remove/Delete a particular Heading - in the below picture I wanna remove "Lists" so whenever my template will be provisioned there will no Heading "Lists". Help would b

  • Advance to Next Stage with "Enter" keystroke

    I have a project in Flash CS3 that has numerous Stages. At the end of each Stage, I have the stop(); actionscript. I need to also implement an advance to nextStage actionscript by just hitting the "Enter" button on the keyboard. Can this be done, and

  • Macbook Pro - Applications wont start without External Display

    Hi all, Apologies if this question has already been answered, but I have spent a lot of time Googling to no avail... I have an early 2011 15" MBP with the following spec: Model Name:          MacBook Pro   Model Identifier:          MacBookPro8,2   P

  • Probe Shows Data, Chart Does Not

    Hello, I have a while loop I am using a USB-6255 to output/input data and it works fine (see part A & B in picture) When I added code (see part C) to input temperature data from a NI-6213 a strange thing happened. The graphs stopped showing data wher