Search code examples
apache-flexflex-spark

How to access a custom ButtonBar button?


I've created a custom Spark ButtonBar. I'd like to show notification badges in it (i.e. a number showing how many notifications that tab has), but I can't figure out how to access the button externally.

I've looked at questions like this one: Hide a Button in a ButtonBar

But that doesn't seem to work, the object I get back from:

btnBarNav.dataGroup.getElementAt(0);

is not an instance of Button or my skin, it's a "GameMenuBarInnerClass0".

Any suggestions on how best to pass some data to my skin to show a number related to the button?


Solution

  • Don't try to access and manipulate the view (your Buttons) directly. Use a model + data binding instead.

    Create a custom skin

    Looks like you already did this, but just for reference: you'll need a custom skin for ButtonBar, and three skins for the ButtonBarButtons: one for the first button, one for the last and one that will apply to all buttons in between.

    Use presentation models for dataprovider

    Create a presentation model that holds a label for the button, perhaps an icon and whatever additional information you'll require in the button. For example:

    class ButtonModel {
        public var label:String;
        [Bindable]
        public var messageCount:int = 0;
    }
    

    Note that I made messageCount bindable so that we can bind to it later.

    Assign a collection of these models as dataprovider of the ButtonBar

    <s:ButtonBar>
        <s:ArrayList>
            <rs:ButtonModel label="Button 1"/>
            <rs:ButtonModel label="Button 2"/>
        </s:ArrayList>
    </s:ButtonBar>
    

    Use presentation properties in the custom skin

    In your custom button skin, you can now bind to the properties of this presentation model. The hostcomponent (ButtonBarButton) has a property data that holds this model instance.

    <s:Label id="labelDisplay"/>
    <s:Label text="{hostComponent.data.messageCount}"/>
    

    Whenever you update the messageCount property on the model, it will automatically be reflected in the button.