views:

122

answers:

3

i have a class that has something like this

public class Foo {
public var f:Function;
public void method(s:String)
{
  f.invoke(s);
}

}

so i need to assign to the f a function that takes an argument f(s), something like

myFoo.f = thefunction
function(s:String)

how to do all this, so it will work correctly ?

+3  A: 

if you are meaning, how to do anonymous functions...

myFoo.f = function( s : String ) {
    //do Stuff to string
}

Then you can use the code you have above.

Gregor Kiddie
boo for weird argument syntax
Jasconius
That is perfectly valid syntax and, within reason, logically equivalent to the usual syntax for named function definitions.
Sly_cardinal
+2  A: 

You should not point anywhere, that your function takes one String argument. If it takes int, or takes 2 arguments, - it would be a runtime error.


myFoo.f = myFunction;

public void function myFunction(s: String): void
{
}

public class Foo {
    public var f:Function;
    public void method(s:String)
    {
        f(s);
    }
}

Pavel Alexeev
+2  A: 

Just to add a nice example:

     import mx.events.FlexEvent;
  public var f:Function;

  protected function application1_creationCompleteHandler(event:FlexEvent):void
  {
   f = addSmile;
   method(' my string');
   f = addFrown;
   method(' my string');

   // Or you can do it straight like this:
   f(' my string');


   // Or alternatively write a function for replacing f
   makeF(addSmile);
   f(' my string');
  }

  public function method(s:String):void
  {
   f(s);
  }

  private function addSmile(s:String):void
  {
   trace (s+' :)'); 
  }
  private function addFrown(s:String):void
  {
   trace (s+' :('); 
  }      

  protected function makeF(newF:Function):void
  {
   f= newF;
  }

will output

 my string :)
 my string :(
 my string :(
 my string :)
Robert Bak