apache-flexactionscript-3functionfilterfunction

String as a function name in as3 / Flex


I have a custom component that extends the spark list.

Inside that custom list, I'm looking to declare a public function that can be called from the main application to filter the result of the list using filterFunction.

My problem is I have multiple filters and I need to pass the function name from the main application as a string ( Or by another way I will learn today! :-) ) like this :

My custom list

<s:List xmlns:fx="http://ns.adobe.com/mxml/2009" 
xmlns:s="library://ns.adobe.com/flex/spark" 
xmlns:mx="library://ns.adobe.com/flex/mx" dataProvider="{listView}">

<fx:Script>
    <![CDATA[

        public function applyFilter(functionName:String):void
        {
            listView.filterFunction = functionName as Function // <-- THIS DOESN'T WORK;
            listView.refresh();
        }

        private function myFilter(obj:Object):Boolean
        {
            // Execution code
        }

        private function anotherFilter(obj:Object):Boolean
        {
            // Execution code
        }

    ]]>
</fx:Script>

Call from my main app

<fx:Script>
<![CDATA[

private function callMyCustomListFilter():void
{
    myCustomList.applyFilter('myFilter');
}

]]>

No error, nothing. The filterFunction is just not executed... Can somebody help? Thanks a lot!


Solution

  • My problem is I have multiple filters and I need to pass the function name from the main application as a string

    Pass the function as a function. Your apply filter function would be something like this:

        public function applyFilter(functionName:Function):void
        {
            listView.filterFunction = functionName;
            listView.refresh();
        }
    

    Then your parent container of the list would have something like this:

    public function myFilter(item:Object):Boolean{
    
    }
    
    private function callMyCustomListFilter():void
    {
        myCustomList.applyFilter(myFilter);
    }
    

    I didn't notice you had the filter functions inside the list component. But, you can make them public and pass them in the same way:

        public function applyFilter(functionName:String):void
        {
            listView.filterFunction = functionName as Function // <-- THIS DOESN'T WORK;
            listView.refresh();
        }
    
        public function myFilter(obj:Object):Boolean
        {
            // Execution code
        }
    
        public function anotherFilter(obj:Object):Boolean
        {
            // Execution code
        }
    
    ]]>
    

    And this:

    <fx:Script>
    <![CDATA[
    
        private function callMyCustomListFilter():void
        {
            myCustomList.applyFilter(myCustomList.myFilter);
        }
    
        ]]>