views:

22

answers:

2

Can anyone provide an example of how to write a callback instead of using an event to communicate between two classes (objects) in Actionscript 3.0?

A: 

What do you mean? A callback is a function that is called in response to an event - in AS parlance, it's an event listener. If you just want classes to communicate, have one of them call a method on the other.

Kelsey Rider
You mean by calling public functions on another class?
redconservatory
I was mostly asking because I read this adobe post, however they didn't post a callback example:http://help.adobe.com/en_US/as3/mobile/WS948100b6829bd5a6d20da321260fed8a52-8000.html
redconservatory
+1  A: 

Just pass a function to another one as parameter to make your callback :

class A {
 function A(){
 }
 // function to be called when work is finished
 private function workDone():void {
  //...
 }
 public function foo():void {
  var b:B=new B();
  b.doWork(workDone); // pass the callback to the work function

  //can also be an anonymous function, etc..
  b.doWork(
   function():void{
    //....
   }
  );
 }
}

class B {
 function B(){
 }
 public function doWork(callback:Function):void{
   // do my work
   callback(); // call the callback function when necessary
 }
}
Patrick
That's great, thanks!
redconservatory