现在的位置: 首页 > 综合 > 正文

Flex的事件

2011年05月14日 ⁄ 综合 ⁄ 共 2549字 ⁄ 字号 评论关闭
Flex的事件C#里的事件相比还是有很大不同的,其中没有代理的概念。
看几段as的代码。
第一步继承Event类,实现自己的事件
package lib 
{
    
import flash.events.Event;
    
    
public class MyEvent extends Event 
    
{
        
public static const FEvent:String ="first";        
        
public static const SEvent:String ="second";        
        
public static const TEvent:String ="third";    
        
private static var type:String;    
        
public function MyEvent(eventType:String)
        
{
            
super(eventType,truetrue);
            type 
= eventType;
        }

        override 
public function clone():Event
        
{
            
return new MyEvent(type);
        }

    }

}


第二步,类定义何时触发事件

package lib
{
    
import flash.events.Event;
    
import flash.events.EventDispatcher;
    
import mx.events.FlexEvent;
    
import flash.display.Sprite;
    [Event(name
="first",type="lib.MyEvent")]
    [Event(name
="second",type="lib.MyEvent")]
    [Event(name
="third",type="lib.MyEvent")]
    
public class MyClass extends EventDispatcher
    
{
        
public function Call1():void
        
{
            
            
this.dispatchEvent(new MyEvent(MyEvent.FEvent));

        }

        
public function Call2():void
        
{
            
            
this.dispatchEvent(new MyEvent(MyEvent.SEvent));

        }

        
public function Call3():void
        
{
            
            
this.dispatchEvent(new MyEvent(MyEvent.TEvent));

        }

    }

}

实例化类,并建立监听

            public function Init():void
            
{
                var mc:MyClass 
= new MyClass();
                mc.addEventListener(MyEvent.FEvent,f);
                mc.addEventListener(MyEvent.SEvent,s);
                mc.addEventListener(MyEvent.TEvent,t);
                mc.Call1();
                mc.Call2();
                mc.Call3();
            }

            
private function f(event:Event):void
            
{
                Alert.show(
"event:f");
            }

            
private function s(event:Event):void
            
{
                Alert.show(
"event:s");
            }

            
private function t(event:Event):void
            
{
                Alert.show(
"event:t");
            }

关于给事件监听方法传递更多参数的问题,Flex的帮助原文如下

Passing additional parameters to listener functions

You can pass additional parameters to listener functions depending on how you add the listeners. If you add a listener with the addEventListener() method, you cannot pass any additional parameters to the listener function, and that listener function can only declare a single argument, the Event object (or one of its subclasses).
If you define an event listener inline (inside the MXML tag), you can add any number of parameters as long as the listener function's signature agrees with that number of parameters.

抱歉!评论已关闭.