R – How to make sure the text of an ActionScript TextInput is updated when the Object property defining that text is updated

actionscript-3apache-flexbindingdata-bindingtext;

Not an easy question to decipher, so let me boil it down. I'm trying to convert an MXML component to an ActionScript Class. The component consists of a Form with a TextInput, TextArea, and two buttons – Save and Cancel, and a Validator for the TextInput, and other logic to handle events that occur. This component is currently extended by several other components.

Now, in the MXML component binding the TextInput text property to a property in an Object was very easy:

<mx:TextInput text="{_itemToEdit.name}" />

But in ActionScript, I'm creating the TextInput and setting the text property before the Object is set, and the TextInput is not being updated:

public var itemToEdit:Object = {};

private var nameInput:TextInput = new TextInput();

public function MyClass()
{
    nameInput.text = itemToEdit.name;
}

How can I make sure that the TextInput text property is bound to the specified property in the Object?

Best Answer

Binding is all about firing change events. you'll need to modify your 'itemToEdit' class to be an EventDispatcher for this hack to work. here goes

//item to edit class
private var _name:String;

public function set name(value:String):void
{
    _name = value;
    dispatchEvent(new Event("NAME_CHANGED"));
}


//whatever the binding class is
private var _itemToEdit:ItemToEdit;
private var _textField:TextField;

public function set itemToEdit(value:ItemToEdit):void
{
    if (_itemToEdit) removeEventListeners();
    _itemToEdit = value;
    if (_itemToEdit) addEventListeners();
}


private function addEventListeners():void
{
    _itemToEdit.addEventListener("NAME_CHANGED", itemToEdit_nameChangedHandler);
    itemToEditChangedHandler(null);
}

private function itemToEdit_nameChangedHandler(event:Event):void
{
    _textField.text = _itemToEdit.name;
}

Obviously this was done just for speed, you'll need custom events and some better names etc, but this is the basic jist.

Related Topic