Flex用一个Event实现多选效果

来源:互联网 发布:qq音速签到软件 编辑:程序博客网 时间:2024/05/16 09:39

用一个Event实现多选效果,其核心的技巧就是使用root这个小东东。说他小,其实他并不小,搞过flash的朋友都知道,root代表的是整个场景,是全局的变量(某种意义上讲比较狭义)。在Flex中某些组件的实例持有root的引用,这个root就是SystemManager,每个Application都有一个SystemManager来控制它的window,这个window在桌面就可能是实实在在的window,而在浏览器中就是其中的一块区域。下面是官方例子程序的源代码(Flex cookbook beta):

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'; //style被赋值                              
           
            if(!event.ctrlKey)
            {
                root.removeEventListener(Item.SELECTED, onSelected);
                root.dispatchEvent(new Event(Item.SELECTED)); //root没有接受到事件
                root.addEventListener(Item.SELECTED, onSelected);
            }
        }
       
        private function onSelected(event:Event):void
        {     //因为root没有接收到事件,所以所选对象也不会接收到事件
            this.txt.styleName = null;//取消style
        }
    }
}

MXML:



 
     .selected
     {
          font-weight: bold;
     }
 
   
      
         
      
   
 
   

 

 


关键的程序也就这3句:
                root.removeEventListener(Item.SELECTED, onSelected);
                root.dispatchEvent(new Event(Item.SELECTED));
                 root.addEventListener(Item.SELECTED, onSelected);

作用也就是避开Item.SELECTED事件所引发的取消style操作。如果你选择的时候按住了ctrl键,那么对象style会被赋予Selected样式。要是没有按住ctrl键,只有你选择的对象逃过了Item.SELECTED事件,而其他对象接受到了Item.SELECTED,因此取消了style。


官方原文及示例代码下载:
http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&productId=2&postId=13327
http://www.adobe.com/cfusion/communityengine/index.cfm?event=downloadFile&productId=2&fileId=578

原创粉丝点击