Avg. Rating 3.3

Problem

I want to deselect items from play list, with out adding any private variables for storing current track nor adding any extra properties or methods to class used to represent item (Value Object), using only 1 existed event, which is being dispatched when some item is selected by user.

Solution

Each item is listening to SELECTED event, in its handler all items setting themselves as not selected. When item is selected by user, or maybe script, system calls item method. In this method, we remove event listener for SELECTED event, setting this item as selected, dispatch ItemDeselect event and after dispatching adding listener to this event again.

Detailed explanation

Here is rough demo source code:

ActionScript (Item class):

package
{
    import flash.events.MouseEvent;
    import flash.events.Event;


    import mx.containers.Canvas;
    import mx.controls.Text;

    public class Item extends Canvas
    {
       
        public static var SELECTED:String = 'Item_SELECTED';
       
        private var txt:Text;
       
        public function Item()
        {
            super();
           
            this.txt = new Text();   
            this.txt.text = 'Click me';       
            this.addChild(this.txt);
           
            this.addEventListener(MouseEvent.CLICK, onClick);
            this.addEventListener(Event.ADDED_TO_STAGE, onAddedStage);
        }
       
        private function onAddedStage(event:Event):void
        {
            root.addEventListener(Item.SELECTED, onSelected);
        }
       
        private function onClick(event:MouseEvent):void
        {
            this.txt.styleName = 'selected';                               
           
            if(!event.ctrlKey)
            {
                root.removeEventListener(Item.SELECTED, onSelected);
                root.dispatchEvent(new Event(Item.SELECTED));
                root.addEventListener(Item.SELECTED, onSelected);
            }
        }
       
        private function onSelected(event:Event):void
        {
            this.txt.styleName = null;
        }
    }
}

MXML:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*">
  <mx:Style>
     .selected
     {
          font-weight: bold;
     }
  </mx:Style>
    <mx:Button label="Add">
       <mx:click>
          <![CDATA[
             this.holder.addChild(new Item());
          ]]>
       </mx:click>
    </mx:Button>
  <mx:Tile id="holder" top="40" />
   
</mx:Application>

 To see the full example, download the zip file associated with this example. This demo project based in my soluton, was created by Diesel Draft.

Report abuse

Related recipes