Making Flex's PopUpMenuButton More Helpful

August 25, 2009 at 06:09 PM | ActionScript | View Comments

If you're anything like me, you cringe every time you think about implementing a popup menu in Flex: the options, PopUpButton and PopUpMenuButton, are both terrible.

For example, PopUpButton makes you jump through the hoops of creating a Menu and PopUpMenuButton forces you to create an event handler just to get the currently selected item.

Well, cringe no more! I've done a bit of hacking on the PopUpMenuButton to make the most common use-case, "showing a list of options", a little bit less painful by adding a 'selectedItem' field:

    <mx:XML id="colors">
        <colors>
            <color name="Red" rgb="0xFF0000" />
            <color name="Green" rgb="0x00FF00" />
            <color name="Blue" rgb="0x0000FF" />
        </colors>
    </mx:XML>
    
    <HelpfulPopupMenu id="colorMenu"
        dataProvider="{colors}"
        labelField="@name"
        showRoot="false" />

    <mx:Label
        color="{XML(colorMenu.selectedItem).@rgb}"
        text="You've chosen: {XML(colorMenu.selectedItem).@name}" />

Which can also be used to set a temporary default option:

    <mx:Script><![CDATA[
        var people:Array = [
            { name: "Bob", age: 16 },
            { name: "Alice", age: 42 },
            { name: "Jo", age: 31 }
        ];
        
    ]]></mx:Script>
    
    <HelpfulPopupMenu id="peopleMenu"
        dataProvider="{people}"
        labelField="name"
        selectedItem="{ { name: '(select a person)', age: null } }"
        showRoot="false" />

    <mx:Label
        visible="{ peopleMenu.selectedItem.age !== null }"
        text="That person is { peopleMenu.selectedItem.age } years old." />

Useful? I'd like to hope so.

You can see a demo by clicking the image below (sorry, I don't actually know the first thing about embedding SWFs into HTML, and I don't feel up to learning right now):

And you can download the source (which is MIT licensed) from more or less the same place: http://wolever.net/~wolever/HelpfulPopupMenu/.

Also, this is a small part of a larger library of helpful ActionScript utilities which I'm going to be releasing… At some point.