本文只針對對初學者,高手就別看了,免得見笑,呵呵。對於AS3事件的註冊、派發、捕獲往往很難理解,我個人認爲最好是反研讀一下Adobe的入門教程。看了之後動手改一些東西吧。我們以FlexStore為例。例如我們想在購物車的mxml頁面增加一個清空所有產品的按鈕。
第一步:首先當然要建立一個 Button拉。
<mx:Button label="清空购物车" id="BTClearCart" fontSize="12" />
第二步:然後在ProductListEvent.as聲明一個事件類型。
public static const REMOVE_CatProducts:String = "removeCatProducts";
第三步:註冊監聽事件。我們在ProductCart.mxml頁面的<mx:VBox>標簽的creationComplete屬性的處理事件中註冊監聽吧。creationComplete可以理解成“加載完畢”。
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:productsView="productsView.*"
horizontalAlign="right"
paddingTop="8"
paddingBottom="8"
paddingRight="4"
paddingLeft="4"
horizontalScrollPolicy="off"
verticalScrollPolicy="off"
creationComplete="creationCompleteHandler();"
>
在Script中:Import事件Import:import flash.events.Event,和增加以下函數:
private function creationCompleteHandler():void
...{
this.addEventListener(ProductListEvent.REMOVE_CatProducts,ClearCartProductsHandler); //註冊監聽事件
}
//處理函數
private function ClearCartProductsHandler(evt:Event):void
...{
this.numProducts = 0; //產品數量清0
this.total = 0; //縂數清0
this.productList.RemoveAllProducts(); //當前“頁”的productList(其實是productList.mxml(可以理解成一個類)的一個實例),調用其函數RemoveAllProducts清空購物車,該函數等一下定義。
}
第四步:在ProductList.mxml(將它理解成類吧。這樣容易理解)定義一個函數如下:
public function RemoveAllProducts():void
...{
this.removeAllChildren();
this.items.length = 0;
}
第五步:在Button派發一個事件出去,派發的事件將被第一步的<VBox>捕獲。Button標簽變成如下:
<mx:Button label="清空购物车" id="BTClearCart" fontSize="12" click="dispatchEvent(new ProductListEvent(ProductListEvent.REMOVE_CatProducts))"/>
順便在這裡説明一下,dispatchEvent就是派發事件函數,一般情況下dispatchEvent 就等於this.dispatchEvent,而在一個mxml文件裏,大多數的情況下的this,都是指當前的mxml,如果一個Button不是直接派發事件,是觸發一個Function,例如 Click="Click的處理function()",然後在“Click的處理function()”這個函數裏面dispatchEvent一個事件,那麽這個dispatchEvent就是this.dispatchEvent了,這個this就是mxml本身,跟按鈕已經沒有關係了。
做完以上五步最後運行程序,我們發現,我們在creationCompleteHandler註冊了監聽事件ProductListEvent.REMOVE_CatProducts(Button刪除所有產品的事件),當點擊Button的時候,派發ProductListEvent.REMOVE_CatProducts事件,派發過程中被<VBox>捕獲並被處理函數ClearCartProductsHandler處理。
本文来自CSDN博客:http://blog.csdn.net/baijinwen/archive/2007/04/05/1552692.aspx