RNJ
RNJ

Reputation: 15552

Flex Give Yes/No box for checkbox deselect

I want to show the user a confirmation box when they deselect a checkbox. My code works although I think it is a bit of a hack. I listen to the checkbox click and then show the alert. Depending on the result I then set the checkbox to be checked again.

My code is

<?xml version="1.0"?>
<s:NavigatorContent xmlns:fx="http://ns.adobe.com/mxml/2009"   xmlns:s="library://ns.adobe.com/flex/spark" >
<fx:Script><![CDATA[
    import mx.controls.Alert;
    import mx.events.CloseEvent;

    private function handleCheckBoxChange(e:Event):void {
        if (!CheckBox(e.target).selected) {
            Alert.show("Are you sure you want to deselect?", "Confirm",
                Alert.YES | Alert.NO, null, handleAlert, null, Alert.YES);
        }
    }

    public function handleAlert(event:CloseEvent):void {
        if (event.detail == Alert.YES) {
            trace("yes clicked");
        }
        else if (event.detail == Alert.NO) {
            cb1.selected = true;
            trace("no clicked");
        }
    }
    ]]></fx:Script>

    <s:CheckBox id="cb1" label="cb1" click="handleCheckBoxChange(event)"/>
</s:NavigatorContent>

There are two things I do not like about this

  1. the code is specific to cb1 and cannot be reused for other checkboxes
  2. the checkbox is deselected when the alert shows. Then when the user clicks no the checkbox is selected again.

What I ideally want is to stop the uncheck event if the user clicks no on the alert box. Is it possible to intercept this in Flex?

Thanks

Upvotes: 1

Views: 1780

Answers (1)

Harry Ninh
Harry Ninh

Reputation: 16718

One solution for your two problems: Create a custom class that extends CheckBox. You cannot use e.stopImmediatePropagation() in click Event because yours is added later. However, if you trace up, you can see in ToggleButtonBase (which is parent of CheckBox) contains a protected function named buttonReleased; this function will do the change for selected value and dispatch a change Event. All you need to do in your new class is overriding this function.

public class AlertCheckBox extends CheckBox
    {
        public function AlertCheckBox()
        {
            super();
        }

        override protected function buttonReleased():void
        {
            if (selected) {
                Alert.show("Are you sure you want to deselect?", "Confirm",
                    Alert.YES | Alert.NO, null, handleAlert, null, Alert.YES);
                return;
            }

            super.buttonReleased();
        }

        public function handleAlert(event:CloseEvent):void {
            if (event.detail == Alert.YES) {
                selected = false;
            }
        }
    }

Upvotes: 2

Related Questions