Dispatching an event from an itemRenderer

Hello everybody,
I can't find what is the best way to do that with spark.
I have a SkinnableComponent that implements IDataRenderer (it owns a button called "addBtn"). I am using it as the itemRenderer of a dataGroup. The skin is a copy of ComboBox skin.
My custom combobox component class (which is using the copied combobox skin) is doing so:
override protected function partAdded(partName:String, instance:Object):void
     super.partAdded(partName, instance);
     if (instance == dataGroup)
          dataGroup.addEventListener("addItem", dispatchAddItemEvent);
override protected function partRemoved(partName:String, instance:Object):void
     super.partRemoved(partName, instance);
     if (instance == dataGroup)
          dataGroup.removeEventListener("addItem", dispatchAddItemEvent);
          trace("removing 'addItem' listener on", dataGroup);
public function dispatchAddItemEvent(e:DynamicEvent):void
     trace("Gotcha!")
And my ItemRenderer component class has this:
override protected function partAdded(partName:String, instance:Object):void
     super.partAdded(partName, instance);
     if (instance == addBtn)
          addBtn.addEventListener(MouseEvent.MOUSE_DOWN, dispatchAddItemEvent);
private function dispatchAddItemEvent(e:MouseEvent):void
     e.stopImmediatePropagation();
     var evt:Event = new Event("addItem", false, false);
     dispatchEvent(evt);
Result is, i never see "Gotcha!" in the console . And yet i know for sure that my IRs' parent is the same dataGroup from upthere. So i dont really understand what's happening here.
Now i know that if i do new Event("addItem", true, true) it would work, but i dont like bubbling . Do i HAVE to ???
Cheers !

Well, I dont see any other approach, unless the virtualLayout = false is set on the list. If the virtualLayout is false, then each itemrender would catch the event and set the property on itself.

Similar Messages

  • 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!

  • 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

  • Dispatching an event from a PDF to AIR?

    I would like to put a button in a PDF using Acrobat, that,
    when clicked, dispatches an event that can be picked up by my
    displaying AIR application. The PDF is being displayed in AIR using
    HTMLLoader in an HTML object.
    Is this possible?

    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 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.

  • How to dispatch an event from the application to the preloader

    HI everyone
                     I've been searching everywhere on the net, and as far as it goes I gotten no answer for this. When the application hit the preinitialize phase, I'm calling the loadStyle method. As you can see I will hold the CreationComplete event until I the swf is ready. What I want to do, is to have a second loading bar in the preloader (no problem here) to show the progress of the swf downloaded, hence the StyleEvent.PROGRESS event. I would like to know how can I dispatch that event to the preloader?
    ///////////////////APPLICATION
                  import mx.events.StyleEvent;
                import mx.styles.StyleManager;
                private function loadStyle():void
                        var eventDispatcher:IEventDispatcher = StyleManager.loadStyleDeclarations("cl/elmelej/mangiare/estilo/estilo.swf");
                        eventDispatcher.addEventListener(StyleEvent.COMPLETE, completeHandler);
                        eventDispatcher.addEventListener(StyleEvent.PROGRESS,progreso);  
                private function completeHandler(event:StyleEvent):void
                        super.initialized = true;
                private function progreso(event:StyleEvent):void
                override public function set initialized(value:Boolean):void
                    // Hold off until the Runtime CSS SWF is done loading.
    ///////////////////////////////////PRELOADER
    virtual public function set preloader(value:Sprite):void
                _preloader = value;
                value.addEventListener(ProgressEvent.PROGRESS, progressHandler);   
                value.addEventListener(Event.COMPLETE, completeHandler);
                value.addEventListener(StyleEvent.PROGRESS, progressHandlerCSS);  
                value.addEventListener(FlexEvent.INIT_PROGRESS, initProgressHandler);
                value.addEventListener(FlexEvent.INIT_COMPLETE, initCompleteHandler);
    As you can see, the preloader is listening to StyleEvent.PROGRESS  events, but I cant dispatch that event to the preloader so that it can react to it. I hope you can help me. Thanks for your time and help
    Sebastián

    Alex,
             Thank you very much for the fast answer, but I'm not an advanced programmer in Flex, so I would need a bit more help from you. I wouldlike you to tell me if it is possible to do what I want to do? and could you be more specific n the information you gave me please?
    I think you mean something like this:
    private function progreso(event:StyleEvent):void
                  (this.systemManager.getChildAt(systemManager.numChildren) as Preloader).getChildAt(XXXXXXXX).dispatchEvent(event)
    /////////////////////// (this.systemManager.getChildAt(systemManager.numChildren) as Preloader)) -------->gets the preloader 
    ///////////////////////(this.systemManager.getChildAt(systemManager.numChildren) as Preloader).getChildAt(XXXXXXXX)     -------------> would get the progressbar (only If I have XXXXXvalue)      
    let me tell you that the method that I posted on the last message was a part of this class:
         public class PreloaderDisplayBase extends Sprite implements IPreloaderDisplay
    PreloaderDisplayBase is my Preloader.
    I hope you can help me.
    Thanks Again
    Sebastián Toro O

  • 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

  • How do I call a function from an Itemrenderer?

    Hi, Im new in flex and I wonder if I can call a function from within an AdvancedDataGridRendererProvider
    for example:
      <mx:AdvancedDataGrid>
        <mx:columns>
            <mx:AdvancedDataGridColumn  dataField="id" />
        </mx:columns>  
        <mx:rendererProviders> 
            <mx:AdvancedDataGridRendererProvider 
                dataField="detail"
                renderer="components.myRendererProvider"  
                columnIndex="2" 
                depth="2"                     
                />     
        </mx:rendererProviders>       
      </mx:AdvancedDataGrid>
    <mx:Script>
         <![CDATA[
              public function outerFunction(){
        ]]>
    </mx:Script>
    myRendererProvider
    <?xml version="1.0" encoding="utf-8"?>
    <mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" paddingLeft="10" paddingRight="2" horizontalGap="2" paddingTop="0">
    <mx:Script>
        <![CDATA[   
         public function callOuterFunction( ){
              how do I call the outerFunction() from here?
        ]]>
    </mx:Script>
        <mx:LinkButton fontSize="13"  fontWeight="bold" click="callOuterFunction( )" label="label"  />
    </mx:HBox>
    thank you in advance.

    There are two ways to call a function from within an ItemRenderer. One way is to dispatch an event from your ItemRenderer and listen for the event in your main application. This approach has the advantage of creating loosely coupled code which is eaiser to maintain and extend if needed, but it takes a bit more work to set things up than using the second aproach lised below. You could also create a custom event to have greater control over what data is sent with the event.
    private function callOuter():void {
         this.dispatchEvent(new MouseEvent());
    The other approach is to call the main application by using parentDocument.
    private function callOuter():void {
         parentDocument.handleItemRenderer();
    Chris

  • 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?

  • Can you send custom events from one form to another?

    I have a compli
    cated application, where I about hundred inp
    uts organized in several input forms. Some of the forms
    require data which has been input in other forms. I have tried to
    dispatch custom events from one form to another, but it dispatches the
    whole form and I only need one or two items.
    Ha anybody else come across such a problem?
    Svend

    One way is to share data in a static singleton

  • Listening to event from custom component

    I have a main.mxml file, and 2 custom components: component1.mxml and component2.mxml
    I want to dispatch an event from component1 and handle it in component 2.
    I'm able to do this by handling the event first in the main.mxml then passing it on.
    But is there a way not to involve main.mxml, and to directly listen to the event from component 1 and handle it in component 2?
    I need to listen the event in actionscript, not mxml.

    You can dig in to custom event handlers
    Best Regards,
    Yogesh

  • Why doesn't the TimeTrait dispatch currentTimeChange event?

    There are cases when I would like a VideoElement's TimeTrait to dispatch currentTimeChange events in addition to complete and durationChange events. I'm wondering what the logic is to not have this trait dispatching this event from the currentTimeChangeEnd protected method? Seems the only way to track an elements current time is to track it at the player level.

    You can setup your own timer and track the currentTime values inside a TimeTrait instance.
    I don't know why the TimeTrait doesn't dispatch the currentTimeChange event, but I suppose that this is intentional - you don't want to provide this kind of utility methods at this low level API level.
    ionflow, why isn't MediaPlayer API good enough for you? Why do you need to get these events at the TimeTrait level?

  • Listening to Events from inside loaded swf

    In Flash Builder 4 I have a swfLoader with which I load swf files. The swf files that get loaded get created in Flash Pro, and I would like to be able to listen for events from the level that they get loaded from. What would I have to specify in the Flash file for the path? Can't seem to be able to specify the right path.
    Thanks a lot for any help!

    I wouldnt say this is elegant but we have been having issues gaining direct access to the SWF's loaded in via OSMF. However I have done setups where I dispatch an event from a SWF and have it bubble up and catch it on the MediaContainer level. Not elegant but works- otherwise may need to make a custom MediaElement and bypass the SWFElement to gain tighter control - seems like there should be a better way, but I havnt found it.

  • Help with dispatching JTable event to underlying components in a cell.

    Hello..
    I have a JTable in which i show a panel with clickable labels.. I found that jTable by default doesnt dispatch or allow mouseevents to be caught by underlying elements..
    i need help with dispatching an event from jTable to a label on a panel in a jTable cell.. below is the code i have come up with after finding help with some websites. but i couldnt not get it right.. my dispatched event seems to go back to the jtable itself ..
    any help or suggestion is appreciated..
    Thanks
    'Harish.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.table.*;
    * @author  harish
    public class tableDemo extends javax.swing.JFrame {
        JTable jTable1;
        testpane dummyPane;
        /** Creates new form tableDemo */
        public tableDemo() {
            initComponents();
            //table settings
            String[] columnNames = {"Task", "Action"," "};
            Object[][] data = { };
            DefaultTableModel model = new DefaultTableModel(data, columnNames) {
              // This method returns the Class object of the first
              // cell in specified column in the table model.
            public Class getColumnClass(int mColIndex) {
                int rowIndex = 0;
                Object o = getValueAt(rowIndex, mColIndex);
                if (o == null)
                    return Object.class;
                } else
                    return o.getClass();
            jTable1 = new javax.swing.JTable(model);
            jTable1.addMouseListener(new MouseAdapter(){
              public void mouseClicked(MouseEvent e){
                  System.out.println("Clicked");
                  handleTableMouseEvents(e);
                 //invokeExternalApp("http://www.pixagogo.com");
              public void mouseEntered(MouseEvent e){
                  System.out.println("Entered");
                  //handleTableMouseEvents(e);
              public void mouseExited(MouseEvent e){
                  System.out.println("Exited");
                  //handleTableMouseEvents(e);
            jTable1.setRowHeight(100);
            jTable1.getTableHeader().setReorderingAllowed(false);
            jTable1.setBackground(new java.awt.Color(255, 255, 255));
            jTable1.setGridColor(new Color(250,250,250));
            jTable1.setShowGrid(true);
            jTable1.setShowVerticalLines(true);
            jTable1.setShowHorizontalLines(false);
            jTable1.setFont(new Font("Arial",0,11));
            jTable1.setMaximumSize(new java.awt.Dimension(32767, 32767));
            jTable1.setMinimumSize(new java.awt.Dimension(630, 255));
            jTable1.setPreferredSize(null);
            jTable1.setBackground(new Color(255,255,255));
            int vColIndex=0;
            TableColumn col = jTable1.getColumnModel().getColumn(vColIndex);
            int width = 100;
            col.setPreferredWidth(width);
            //add item to 2nd cell       
            Vector vec = new Vector();
            vec.addElement(null);
            dummyPane = new testpane();
            vec.addElement(dummyPane);
            ((DefaultTableModel)jTable1.getModel()).addRow(vec);
            jTable1.repaint();
            this.getContentPane().add(jTable1);
            jTable1.getColumn("Action").setCellRenderer(
              new MultiRenderer());
        protected void handleTableMouseEvents(MouseEvent e){
            TableColumnModel columnModel = jTable1.getColumnModel();
            int column = columnModel.getColumnIndexAtX(e.getX());
            int row    = e.getY() / jTable1.getRowHeight();
            testpane contentPane = (testpane)(jTable1.getModel().getValueAt(row, column));
            // get the mouse click point relative to the content pane
            Point containerPoint = SwingUtilities.convertPoint(jTable1, e.getPoint(),contentPane);
            if (column==1 && row==0)
            // so the user clicked on the cell that we are bothered about.         
            MouseEvent ev1 = (MouseEvent)SwingUtilities.convertMouseEvent(jTable1, e, contentPane);
            //once clicked on the cell.. we dispatch event to the object in that cell
         jTable1.dispatchEvent(ev1);
        private void initComponents() {
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-528)/2, (screenSize.height-423)/2, 528, 423);
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new tableDemo().show();
        // Variables declaration - do not modify
        // End of variables declaration
        class testpane extends JPanel{
            public testpane(){
            GridBagConstraints gridBagConstraints;
            JPanel testpane = new JPanel(new GridBagLayout());
            testpane.setBackground(Color.CYAN);
            JLabel lblTest = new JLabel("test");
            lblTest.addMouseListener(new MouseAdapter(){
              public void mouseClicked(MouseEvent e){
                  System.out.println("panelClicked");
              public void mouseEntered(MouseEvent e){
                  System.out.println("panelEntered");
              public void mouseExited(MouseEvent e){
                  System.out.println("panelExited");
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 0;
            gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
            testpane.add(lblTest,gridBagConstraints);
            this.add(testpane);
    class MultiRenderer extends DefaultTableCellRenderer {
      JCheckBox checkBox = new JCheckBox();
      public Component getTableCellRendererComponent(
                         JTable table, Object value,
                         boolean isSelected, boolean hasFocus,
                         int row, int column) {
        if (value instanceof Boolean) {                    // Boolean
          checkBox.setSelected(((Boolean)value).booleanValue());
          checkBox.setHorizontalAlignment(JLabel.CENTER);
          return checkBox;
        String str = (value == null) ? "" : value.toString();
        return super.getTableCellRendererComponent(
             table,str,isSelected,hasFocus,row,column);
        return (testpane)value;
    class MultiEditor implements TableCellEditor {
      public MultiEditor() {
      public boolean isCellEditable(EventObject anEvent) {return false;}
      public boolean stopCellEditing() {return true;}
      public Object getCellEditorValue() {return null;} 
      public void cancelCellEditing() {}
      public boolean shouldSelectCell(EventObject anEvent) {return false;}
      public Component getTableCellEditorComponent(JTable table, Object value,
                  boolean isSelected, int row, int column) {
        if (value instanceof testpane) {                       // ComboString
          System.out.println("yes instance");
        return null;
      public void addCellEditorListener(javax.swing.event.CellEditorListener l) {
      public void removeCellEditorListener(javax.swing.event.CellEditorListener l) {
    }

    any help on this.. anybody. ?

  • Passing events from externally-loaded SWFs

    Hi,
    We have an externally-loaded swf that acts as a kind-of-a slide show.  After a user selects a particular subject from a mxml-based "menu" application, they push "buttons" in the SWF to go through a presentation, then on the last frame of the swf, I'd like to unload the swf and replace it with another "mxml" application.  How can this be done?  I have not tried to pass/capture events "up" from an externally-loaded swf before.
    Thanks,
    Doug

    Do you own those SWFs?  If so, they should dispatch an event from a known
    place like a SlideShowManager or something like that.
    Other folks "cheat" and bubble events or dispatch off of the systemManager
    and/or top-level application.

Maybe you are looking for