LinkBar tied to component states

I just did a quick extension of the Flex LinkBar so you can tie it to the states of a component. I haven’t tested it throughly yet, so if you find anything weird in there, let me know…
usage:

<components:StateLinkBar dataProvider="{states}"/>


you can download the code here, or just cut and paste from below:

package view.components
{
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import mx.controls.LinkBar;
	import mx.core.UIComponent;
	import mx.events.StateChangeEvent;
	public class StateLinkBar extends LinkBar
	{
		private var measurementHasBeenCalled:Boolean = false;
		private var __pendingStates:Array;
		private var __states:Array;
		public function StateLinkBar()
		{
			super();
			labelField = "name";
		}
		override public function set dataProvider(value:Object):void{
			super.dataProvider = value;
			if(value==parentDocument.states){
				setStateListeners(value as Array);
			}
		}
		override protected function commitProperties():void{
			super.commitProperties();
			if(!measurementHasBeenCalled && __pendingStates){
				measurementHasBeenCalled = true
				setStateListeners(__pendingStates);
			}
		}
		override protected function clickHandler(event:MouseEvent):void{
			if(__states){
				var index:int = getChildIndex(DisplayObject(event.currentTarget));
				var uic:UIComponent = parentDocument as UIComponent;
				uic.currentState = __states[index].name;
				hiliteSelectedNavItem(index);
			}
			super.clickHandler(event);
		}
		private function setStateListeners(arr:Array):void{
			if(!measurementHasBeenCalled){
				__pendingStates = arr;
				invalidateProperties();
				return;
			}
			var p:UIComponent = parentDocument as UIComponent;
			if(p !=null){
				__states = arr;
				//setup listeners
				p.addEventListener(StateChangeEvent.CURRENT_STATE_CHANGE,onParentStateChange);
			}
		}
		private function onParentStateChange(event:StateChangeEvent):void{
			var newState:String = event.newState;
			if(__states){
				var max:Number = __states.length;
				for (var i:Number=0;i<max;++i){
					if(__states[i].name==newState){
						selectedIndex = i
						hiliteSelectedNavItem(i);
					}
				}
			}
		}
	}
}
This entry was posted in Flash & Actionscript. Bookmark the permalink. Trackbacks are closed, but you can post a comment.