Xml – Duplicate complex MXML binding in ActionScript

apache-flexdata-bindingmxml

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";
???

Best Answer

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.

Related Topic