0 Replies Latest reply on Mar 14, 2007 10:19 AM by Mark_Ingram

    First attempt at actionscript component

    Mark_Ingram
      Hi, I've just created my first flex / actionscript component, and wondered if you would mind casting an eye over it and giving it some critism! It's basically a PopUpMenuButton - but the original label is permanently displayed (i.e. if your label is "Colour", after selecting from the menu it will say, "Colour: Red"). Here is the code - the one area I had trouble with was registering for a change event on the text field of the button - I wanted to know when someone changed the label, but I had to resort to overriding the label property instead.

      (see the line, this.textField.addEventListener(Event.CHANGE, onTextFieldChange);)

      quote:

      import mx.controls.PopUpMenuButton;
      import flash.events.Event;
      import mx.events.MenuEvent;
      import mx.controls.Menu;
      import mx.events.FlexEvent;

      public class PopUpMenuButtonLabel extends mx.controls.PopUpMenuButton
      {
      public function PopUpMenuButtonLabel()
      {
      super();

      addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
      addEventListener(MenuEvent.ITEM_CLICK, onItemClick);
      }

      private function onItemClick(event:MenuEvent):void
      {
      onSelectedChanged();
      }

      public override function get label():String
      {
      return super.label;
      }

      public override function set label(newLabel:String):void
      {
      super.label = newLabel;
      this.onTextFieldChange();
      }

      private var m_label : String = "";
      private var m_created : Boolean = false;

      private function onCreationComplete(event:FlexEvent):void
      {
      // This event doesn't get fired for some odd reason
      //this.textField.addEventListener(Event.CHANGE, onTextFieldChange);

      m_created = true;

      var popUpMenu:Menu = Menu(this.popUp);
      popUpMenu.selectedIndex = 0;
      onSelectedChanged();
      }

      private var m_ignoreTextFieldChange : Boolean = false;
      private var m_previousSelectedIndex : Number = -1;

      private function onSelectedChanged():void
      {
      var popUpMenu:Menu = Menu(this.popUp);
      var selectedItem:Object = popUpMenu.selectedItem;

      if (selectedItem != null)
      {
      m_ignoreTextFieldChange = true;
      this.label = m_label + ": " + selectedItem.label;
      m_ignoreTextFieldChange = false;
      m_previousSelectedIndex = popUpMenu.selectedIndex;
      }
      }

      private function onTextFieldChange():void
      {
      if (!m_ignoreTextFieldChange)
      {
      // The label has changed, update the original, and signify a change
      m_label = this.label;
      if (m_created)
      {
      var popUpMenu:Menu = Menu(this.popUp);
      popUpMenu.selectedIndex = m_previousSelectedIndex;
      this.onSelectedChanged();
      }
      }
      }
      }


      Thank you!