Delegates in AS3

Categories: actionscript
Written By: sebi

Maybe you saw a few implementation of delegation in as3. I saw. But as as the changes in as3 made the traditional usage of the Delegate class unnecessary, you could wonder, where to use it.

I show you, where I found the delegation very useful. One word, filterFunction. The ArrayCollection class has this property, you can define a method here, to filter the items in the ArrayCollection. Sadly, the way you declare it, like lcv1.filterFunction = filterText doesn’t allow to add arguments to the method it calls. When you want a dynamic filter instead of the static, you can use delegates here quite nicely.

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
				layout="vertical"
				applicationComplete="init()">
	<mx:Script>
		<![CDATA[
			import mx.collections.ListCollectionView;
			import mx.collections.ArrayCollection;
 
			[Bindable]		
			protected var ac:ArrayCollection;
			protected function init():void
			{
				ac = new ArrayCollection()
				for( var i:int = 0; i < 21; i ++ )
				{
					ac.addItem( { data:i, label: "item " + i.toString() } )
				}
			}
 
			protected function refreshFilter():void
			{
				ac.filterFunction = Delegate.create( filterText, filterTextInput.text )
				ac.refresh()
			}
 
			protected function filterText( item:Object, search:String ):Boolean
			{
				return item.label.indexOf( search ) > -1
			}
 
		]]>
	</mx:Script>
	<mx:DataGrid dataProvider="{ac}" />
	<mx:TextInput id="filterTextInput" change="refreshFilter()" />
</mx:WindowedApplication>

Of course, this is not the best example, but you can get the idea, how to create filters, without the need of a class level variable, or anything.

package
{
    public class Delegate
    {
        public static function create( handler:Function, ...args ):Function
        {
            return function(...innerArgs):*
            {
                return handler.apply( this, innerArgs.concat( args ) );
            }
        }
    }
}

Comments are closed.