2009-07-24 64 views
2

我有一個由可選控件(單選按鈕) 和文本輸入組成的自定義組件。我想執行一些邏輯以響應來自這兩個控件的 更改事件,但在此之後,我希望 在複合組件的更改處理程序 上註冊的任何內容都有更改以處理事件。問題是,當我 重新分派事件時,事件目標已更改爲我的自定義 組件,從而失去原始事件的目標。組合自定義組件上的Flex 3事件傳播?

這裏是我的自定義組件:

<?xml version="1.0" encoding="utf-8"?> 
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" label="{[email protected]}" data="{[email protected]()}"> 

    <mx:Script> 
     <![CDATA[ 
      import mx.controls.RadioButtonGroup; 
      [Bindable] 
      public var selected: Boolean; 
      [Bindable] 
      public var text: String; 
      [Bindable] 
      public var listItem: XML; 
      [Bindable] 
      public var group: RadioButtonGroup; 

      private function onSelectionChange(event: Event): void { 
       selected = event.target.selected; 
       dispatchEvent(event); 
      } 

      private function onTextChange(event: Event): void { 
       text = event.target.text; 
       dispatchEvent(event); 
      } 
     ]]> 
    </mx:Script> 

    <mx:RadioButton group="{group}" label="{label}" selected="{selected}" change="onSelectionChange(event)"/> 
    <mx:TextInput width="100%" 
        maxChars="{[email protected]}" 
        enabled="{selected}" 
        visible="{listItem.hasOwnProperty('specify')}" 
        includeInLayout="{visible}" 
        change="onTextChange(event)"/> 
</mx:HBox> 

在接收來自這個組件的改變事件的事件處理程序,我 看到event.target是SpecifyRadioButton的一個實例,而不是 的TextInput或單選按鈕,因爲我期待。我應該如何宣傳 活動以獲得我想要的內容?

Getting event [Event type="change" bubbles=false cancelable=false eventPhase=2] 
from question0.tabSurvey.questionForm.questionContainer.Single94.VBox95.SpecifyRadioButton111 

回答

3

而不是重新調度原始事件,創建一個新的事件,然後將原來的事件作爲origEvent財產。 SpecifyRadioButton派發的新事件既可以是擴展Event的自定義事件類,也可以是懶惰的,只需使用mx.events.DynamicEvent。

例子:

import mx.events.DynamicEvent; 

private function onSelectionChange(event: Event): void { 
    selected = event.target.selected; 
    var newEvent:DynamicEvent = new DynamicEvent(Event.CHANGE); 
    newEvent.origEvent = event; 
    dispatchEvent(newEvent); 
} 

然後,在你的處理程序SpecifyRadioButton.change事件,引用event.origEvent財產。

2

它是有道理的事件的目標將SpecifyBadioButton,因爲這就是調度事件。

TextInput組件的「更改」事件設置爲不起泡,這意味着它可以由與其相同的組件中的偵聽器進行偵聽,但無法在其他位置進行偵聽。如果你想讓變化事件冒泡,你將不得不擴展TextInput類(或者使用像Mate這樣的漂亮的東西)。

package { 

    import flash.events.Event; 
    import mx.controls.TextInput; 

    public class CarbonatedTextInput extends TextInput { 
     public function CarbonatedTextInput() { 
      super(); 
      addEventListener(Event.CHANGE, forceBubbles); 
     } 

     /* 
      We have to remove the event listener before we 
      dispatch the new event (with bubbles!) because 
      otherwise our listener in the constructor would 
      catch us and put us in an endless loop... 
      resulting in a **STACK OVERFLOW** 
     */ 
     protected function forceBubbles(e:Event):void { 
      removeEventListener(Event.CHANGE, forceBubbles); 
      dispatchEvent(new Event(Event.CHANGE, true)); 
      addEventListener(Event.CHANGE, forceBubbles); 
     } 
    } 
}