tags:

views:

259

answers:

2

Should programmatic logic be inserted into an MXML Attribute? I have a few Buttons which may or may not dispatch events based on the state of related components (e.g. DataGrid or List), and I'm trying to figure out if the logic is simple enough to simply embed in one of the Event attributes in the MXML.

Here's how I've been doing things:

<mx:Script>
    <![CDATA[
        private function sendEvent1():void {
            if (list.selectedIndex != -1) {
                dispatchEvent(new Event("click!"));
            }
        }
    ]]>
</mx:Script>
<mx:List id="list" dataProvider={listData} />
<mx:Button label="Click!" click="sendEvent1()" />

In this example, the ActionScript contained in the Script tag contains the logic for determining whether or not the event should be dispatched.

The Button, however, can be modified a bit, removing the need for the sendEvent1 function:

<mx:Button label="Click!" click="if (list.selectedIndex != -1) dispatchEvent(new Event("click!")" />

Ignoring some of the obvious issues in these snippets (e.g. static strings, missing code for the data provider, etc.), there are a few concerns I have with the second example:

  • The MXML is less readable (it gets long and cluttered)
  • As more function calls are required for clicking the Button, the logic in the MXML becomes much more unwieldy.
  • Embedding logic in the MXML makes it less intuitive (for me at least). If I want to know the logic of the MXML, I'm more inclined to look in the Script tag, where I expect the ActionScript.

Are there other pros behind inserting logic in an MXML attribute? I've been seeing this use more and more often, and I want to make sure I'm not missing any compelling reasons to change how I've been doing things.

+1  A: 

I can't think of any true benefit to adding logic to the MXML code if the code is more than one line long, like and alert or possibly at most, unconditionally setting a variable. Imagine trying to read a switch statement inline.

Jeff Pinkston
+1  A: 

It's not a good idea to put more than one liner inline. Hard to read, hard to debug. To make the inline code more readable though, put it inside the curly braces and write it in multiple lines.

Yakov Fain