使用自定义事件并随事件传递数据

如何使用自定义事件来随事件传递数据?

首先必须创建一个继承与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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值