On using a invalidation approach in Flex

When creating custom components it is better to defer any processing in your mutators(read setters) to the validation phase(s) of the Flex framework. This can be beneficial for many reasons such as performance, timing, etc. Consider the possibility that x gets set before y but that x needs y when x is set at runtime when you have no control over when these get set due to asynchronicity or some such. Also, it can cut down on the use of bindable variables, a performance bottleneck.

Enter the Flex component life cycle. I’m not going to cover the whole life cycle, but suffice it to say that in the life of a component it can enter a invalidation/validation phase. Flex uses these phases to synchronize changes. Note that this entrance is not necessarily a one-time thing either. So how do we make use of this? One approach is to use a method called invalidateProperties(). This tells the SDK that during the next cycle of the circle of life for the component to call commitProperties(). We do not call commitProperties() directly, rather we let the Flex SDK do that. Hence the notion of invalidation and validation phases. Ok, some code!

This is a typical pattern for coding a mutator in your component for a property called zinger:
//a flag to flag changes, this makes the circle of life more efficient
private var:Boolean zingerChanged;
//the actual var stuff
private var:int _zinger;
public function set zinger(val:int):void {
if( val != _zinger) {
_zinger = val;
zingerChanged = true;
invalidateProperties();
}
}
public function get zinger():int {
return _zinger;
}
//now overrride
override protected function commitProperties():void {
super.commitProperties();
if( zingerChanged ) {
zingerChanged = false;
//do your logic and such here concerning a change in zinger
}
}

Ok, there you have it. Aside from some possible typos, that should get you on your way to better performing components.

Cheers!

DK


No comments yet. Be the first.

Leave a reply