Avg. Rating 3.3

Problem

I have created a custom class in ActionScript which I instantiate, use, and modify throughout my application. However, modifications to the class members are not reflected in my application after instantiation, even though I've marked them as "bindable".

Solution

To achieve simple data-binding in an application, it is often enough to mark the target variables as "bindable". However, if these variables are member variables of a class that you've instantiated, we must do more than simply mark them as "bindable". We must use the bindProperty() function provided by the BindingUtils class.

Detailed explanation

The bindProperty() function prototype is...

bindProperty(site:Object, prop:String, host:Object, chain:Object, commitOnly:Boolean = false):ChangeWatcher


A typical use of this function involves attaching the site's property to the host's property.  For instance, if I wanted my text box, labeled "nameBox", to reflect changes to a user's name, property someUser.firstName, then I would place...

// binds a 'text' field on a text-box labeled 'nameBox' to
// the property 'firstName' on some object 'someUser'
bindProperty(nameBox, "text", someUser, "firstName");


...somewhere in an initialization function, and call that on creationComplete.  Finally, I would place the [Bindable] tag on the property that I want to bind in the class file.

public class Dog
{
	// allows this variable to be binded using
	// the bindProperty method
	[Bindable] public var name:String;

	public function Dog()
	{
	}  // Dog
}  // class declaration


Here is a very simple Flex example illustrating this technique...

main.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" verticalAlign="middle" creationComplete="init()">

	<mx:Script>
		<![CDATA[
			import mx.binding.utils.BindingUtils;

			[Bindable] private var myDog:Dog = new Dog();


			private function init():void
			{
				BindingUtils.bindProperty(dogNameText, "text", myDog, "name");
			}  // init

			private function changeDogName():void
			{
				myDog.name = dogNameInput.text;
			}  // changeDogName
		]]>
	</mx:Script>

	<mx:Text id="dogNameText" text="{myDog.name}" fontSize="12" />
	<mx:Spacer height="50" />
	<mx:HBox>
		<mx:Label text="Change my dog's name to: " />
		<mx:TextInput id="dogNameInput" />
	</mx:HBox>
	<mx:Button label="change name" click="changeDogName()"/>

</mx:Application>

 

Dog.as

package
{
	public class Dog
	{
		[Bindable] public var name:String;
		
		public function Dog()
		{
			name = "Pluto";
		}  // Dog
	}  // class declaration
}  // package


See the complete documentation for BindingUtils in the Adobe LiveDocs for Flex 3.

 

Report abuse

Related recipes