views:

944

answers:

3

Hi, I have a project in which i need to pop up an alert to the user before a combobox value is changed. This feature is to allow the user to stay in current state if modifications were not saved. Meaning that the user will be able to cancel the change.

I have sub classed ComboBox and tried to hook on ITEM_CLICK of ComboBox.dropdown but this event is triggered after the value is changed. Also, I've tried MOUSE_CLICK ans MOUSE_DOWN but without success.

In my code, I have added a "preChange" event to my CustomComboBox. This event should be triggered before a change is made. Also, I've introduced a method called commitChange that will be called manually to actually commit the change.

How can I achieve the desired result?

A: 

This is how I've done it:

<?xml version="1.0" encoding="utf-8"?>
<mx:ComboBox xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="onComplete();">
 <mx:Script>
  <![CDATA[
   import mx.events.CloseEvent;
   import mx.controls.Alert;
   import mx.events.ListEvent;
   private function onComplete():void {
    addEventListener(ListEvent.CHANGE, onChange);
    persistLastIndex();
   }

   private var _lastIndex:Number = 0;

   private function persistLastIndex():void {
    _lastIndex = selectedIndex;
   }

   private function onChange(event:ListEvent):void {
    Alert.show("Are you sure you want to change the selection?", "", Alert.YES|Alert.NO, null, onAlertClicked);
   }

   private function onAlertClicked(event:CloseEvent):void {
    if ( event.detail == Alert.NO ) {
     selectedIndex = _lastIndex;
    } else {
     _lastIndex = selectedIndex;
    }
   }

  ]]>
 </mx:Script>
</mx:ComboBox>

And to call it:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
 xmlns:rad="uk.co.rad.*">
 <rad:MyComboBox>
  <rad:dataProvider>
   <mx:Array>
    <mx:Object data="1" label="Value 1" />
    <mx:Object data="2" label="Value 2" />
   </mx:Array>
  </rad:dataProvider>
 </rad:MyComboBox>
</mx:Application>

Hope this helps.

radekg
A: 

Basically I needed an event before the change is made. I guess that'll do for now thought ...

I did modify your code to make it fire the preChange event when a change occur, stop the event propagation, and only after the change is really made fire the CHANGE event ..

Thanks for your prompt answer.

Ofir Herzas
A: 

The easiest way to do it is to add two listeners to Event.CHANGE on the ComboBox, then set the priority of the handler you want to fire prior to the change as a negative value. For example:

myComboBox.addEventListener(Event.CHANGE, preChange, false, -100);
myComboBox.addEventListener(Event.CHANGE, postChange, false, 100);

The order of event dispatching:

  1. preChange(event:Event)
  2. inherited change events (automatically have a default priority of 0)
  3. postChange(event:Event)
Civil Disobedient