views:

649

answers:

3

MXML lets you do some really quite powerful data binding such as:

<mx:Button id="myBtn" label="Buy an {itemName}" visible="{itemName!=null}"/>

I've found that the BindingUtils class can bind values to simple properties, but neither of the bindings above do this. Is it possible to do the same in AS3 code, or is Flex silently generating many lines of code from my MXML? Can anyone duplicate the above in pure AS3, starting from:

var myBtn:Button = new Button();
myBtn.id="myBtn";
???
A: 

I believe flex generates a small anonymous function to deal with this.

You could do similar using a ChangeWatcher. You could probably even make a new anonymous function in the changewatcher call.

Marc Hughes
+2  A: 

The way to do it is to use bindSetter. That is also how it is done behind the scenes when the MXML in your example is transformed to ActionScript before being compiled.

// assuming the itemName property is defined on this:
BindingUtils.bindSetter(itemNameChanged, this, ["itemName"]);

// ...

private function itemNameChanged( newValue : String ) : void {
  myBtn.label   = newValue;
  myBtn.visible = newValue != null;
}

...except that the code generated by the MXML to ActionScript conversion is longer as it has to be more general. In this example it would likely have generated two functions, one for each binding expression.

Theo
+1  A: 

You can also view the auto-generated code that flex makes when it compiles your mxml file, by adding a -keep argument to your compiler settings. You can find your settings by selecting your projects properties and looking at the "Flex Compiler" option, then under "Additional compiler arguments:" add "-keep" to what is already there.

Once done Flex will create a "generated" directory in your source folder and inside you'll find all teh temporary as files that were used during compilation.

defmeta