« Messaging from Java to Flex without JMS | Main | How to vertically center images in jCarousel and Thickbox3. »

Understanding and improving Flex bindings

Data binding is the magical process by which changes in a data model are instantly exposed to views. It works because of the Flex framework that generates a lot of code for you under the hood.

Let's see what flex does when we set a property [Bindable] by using the setter and getter method like this:

public class MyComponent
{

private var _myProp:Object;

[Bindable]
public function get myProp( ) : Object
{
return _myProp;
}

public function set myProp( value:Object ) : void
{
_myProp = value;
}

}

Now when you set the myProp to some value:

var myCompInstance:MyComponent = new MyComponent( );
var myPropToSet:Object = new Object( );
myCompInstance.myProp = myPropToSet;

you are going to invoke the statement "function set myProp( value:Object )".
But Flex will do something different.
First of all it will compare the new value, myPropToSet with the last inserted _myProp, by invoking the getter function, and if the value result will be the same, the setter will not be invoked.
All of this because you have marked the property as [Bindable].
So if run a code like this:

myCompInstance.myProp = myPropToSet; <-- only this will be set
myCompInstance.myProp = myPropToSet;
myCompInstance.myProp = myPropToSet;

only the first value will be set.
So if you have the necessity to reset a value on a bindable property you have to define your custom binding:

[Bindable(event="myCustomChangeEvent")]
public function get myProp( ) : Object
{
return _myProp;
}

public function set myProp( value:Object ) : void
{
_myProp = value;
dispatchEvent( new Event( "myCustomChangeEvent" ) );
}

Now you can set the property every time you want and any item who is watching will be regularly notified.

TrackBack

TrackBack URL for this entry:
http://blog.comtaste.com/mt-tb.cgi/88

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

About

This page contains a single entry from the blog posted on March 27, 2009 3:31 PM.

The previous post in this blog was Messaging from Java to Flex without JMS.

The next post in this blog is How to vertically center images in jCarousel and Thickbox3..

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33