如何使用自定义事件来随事件传递数据?
首先必须创建一个继承与flash.events.Event的类,再创建欲与之派发的属性。必须调用super方法,确保事件对象的实例化,最后重载clone方法就行了。
为什么要使用自定义事件呢?它可以满足我们不必通过派发事件的对象来访问相应的数据。
csdn插件挂了,直接放上代码吧。
package cn.ipanel.event
{
import cn.ipanel.Person;
import flash.events.Event;
public class CustomPersonEvent extends Event
{
public var person:Person;
public static const NAME:String="custompersonevent";
public function CustomPersonEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false, person:Person=null)
{
super(type, bubbles, cancelable);
this.person=person;
}
override public function clone():Event
{
return new CustomPersonEvent(type, bubbles, cancelable, person);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"
width="400"
height="300">
<mx:Script>
<![CDATA[
import cn.ipanel.event.CustomPersonEvent;
[Bindable]
private var _person:Person;
public function set person(person:Person):void
{
this._person=person;
}
public function dispatchPersonEvent():void
{
var person:Person=new Person();
person.age=25;
person.name="huangjx";
dispatchEvent(new CustomPersonEvent(CustomPersonEvent.NAME, true, false, person));
}
]]>
</mx:Script>
<mx:Button x="151"
y="176"
label="派发自定义person事件" click="dispatchPersonEvent()"/>
</mx:Canvas>
在application里面加上上面组件和下面代码
<mx:Script>
<![CDATA[
import cn.ipanel.event.CustomPersonEvent;
import cn.ipanel.Person;
private function init():void{
var _person:Person=new Person();
_person.age=1;
_person.name="huangjx";
myPerson.person=_person;
addEventListener(CustomPersonEvent.NAME,CustomPersonEventHandler);
}
private function CustomPersonEventHandler(e:CustomPersonEvent):void{
trace(e.person.age+e.person.name);
}
]]>
</mx:Script>