tags:

views:

580

answers:

2

Which is a much better practice in binding a value in Flex?

A: 

In most cases properties are better for a few reason:

1) It's easy to set property in mxml. For example:

<mx:Button label="Bla">

, where label is public property. And it's not possible with setter/getter function, you have to call setLabel("Bla") from the script.

2) Properties are basically the same functions as setters and getters. I like create one more extra private method when setter gets complicated.

public function get label():String
{
    return _label;
}

public function set label(value:String):void
{
   setLabel(value);
}

private function setLabel(value:String):void
{
     if(value == "") {
         // do something
     } else {
         _label = value;
         remeasureComponent(); // or whatever
     }
}

3) It's built in into language so use it. Plus it looks nicer to say object.label = "Bla" than object.setLabel("Bla")

zdmytriv
+5  A: 

Exposing a bindable public property using either of the approaches below are considered best practice in Flex:

[Bindable] public var dataProvider:Object;
[Bindable] public function get dataProvider():Object { ... }

The get/set function pairs are a little more flexible then regular public properties. You can still easily make the property bindable by annotating the get function with the [Bindable] tag. However you can implement some custom logic in the "set" function, including setting dirty flags and invalidating properties, size or the display list. eg:

private var _dataProvider:Object;
private var dataProviderChanged:Boolean;
public function set dataProvider(value:Object):void
{
    if (_dataProvider != value)
    {
        _dataProvider = value;
        dataProviderChanged = true;
        invalidateProperties();
    }
}
[Bindable] public function get dataProvider():Object
{
    return _dataProvider;
}

This pattern is used heavily in Flex framework components. The invalidation model is very clean and also leads to the best performance in your custom components.

You can also specify a custom event for the bindable property so you can trigger its binding from multiple places, instead of just by invoking the setter:

[Bindable( "dataProviderChanged" )]
public function get dataProvider():Object
{
    return _dataProvider;
}

public function someRandomMethod():void
{
     // ...
     // pretend that we just finished some processing
    _dataProvider = newValue;
    dispatchEvent( new Event( "dataProviderChanged" ) );
}

This also works nicely if you want to make the property read-only, meaning that it has no matching "set" method.

cliff.meyers
Nice answer Thank you
Rahul Garg
Ditto. Nice answer.
Mike Sickler