看过ActionScript 3.0 Essential Training, 找了其中一个例子填充一下博客. 为自定义的类添加侦听事件是一件很简单的事情, 只要有耐心就OK了^_^ ... 请看例子, 最下面提供源文件下载:
--------------------------------------------------------
package {
import flash.display.MovieClip;
import com.lynda.as3et.ProgrammingBasics.InventoryItem;//导入自定义的类
import flash.events.Event;
public class ProgrammingBasics extends MovieClip {
//构造函数
public function ProgrammingBasics ( ) {
var myItems:InventoryItem = new InventoryItem(19);
//侦听Event.CHANGE事件,当myItems.quantity的值改变时执行onInventoryChange()函数
//以下这句也可以为: myItems.addEventListener("change", onInventoryChange);
myItems.addEventListener(Event.CHANGE, onInventoryChange);
//修改myItems.quantity的值,一旦执行这句,便触发上面的侦听器事件
myItems.quantity = -100;
}
//侦听器处理函数
private function onInventoryChange(event:Event):void {
trace(event.currentTarget.quantity);
}
}
}
自定义的类:
package com.lynda.as3et.ProgrammingBasics {
import flash.events.EventDispatcher;
import flash.events.Event;
public class InventoryItem extends EventDispatcher {
private var _quantity:Number;
//构造函数
public function InventoryItem(quantity:Number) {
_quantity = quantity;
}
//这个函数用于获得_quantity的值,用点语法使用,如: myItems.quantity
public function get quantity():Number {
return _quantity;
}
//这人函数用于修改_quantity的值,用法: myItems.quantity = 100;
public function set quantity(value:Number):void {
_quantity = value;
// --- 最关键就是这里 ---
//添加侦听器,侦听是否执行了如 myItems.quantity = 100 的语句
//这句也可以为: dispatchEvent(new Event("change"));
dispatchEvent(new Event(Event.CHANGE));
}
}
}
--------------------------------------------------------
点击进行下载: 压缩包下载
回复Comments
{commenttime}{commentauthor}
{CommentUrl}
{commentcontent}