Object A calls method M of object B, passing it two callbacks for two cases: cbYes and cbNo.
B, in turn, performs a web service async call, creating Object C (api) instance with the only callback: method N of B. This callback will decide which of the two callbacks to call.
I store cbYes and cbNo functions as B’s private vars of type Function.
How can I call either callback? They’re not children of B, so syntax B[cbYes](); is not the way. Unreal code example:
class A {
public function Smth() {
var instB:B = new B( cbYes, cbNo);
}
public function cbYes( e:Event) { doSomething(); }
public function cbNo( e:Event) { doSomething(); }
}
class B {
private var _cb1:Function;
private var _cb2:Function;
public function B( cb1, cb2) {
_cb1 = cb1; _cb2 = cb2;
var worker:C = new C();
C.apiMethod123( cbAfterCall);
}
public function cbAfterCall( Result:*) {
if( Result = 1) {
// here I need to call callback from _cb1
} else {
// here I need to call callback from _cb2
}
}
}
class C {
private var _Callback:Function;
public function C() { }
public function apiMethod123( cb:Function) {
this._Callback = cb;
// create a URLLoader or a Loader and do a web service call
}
public function urlCallback( e:Event) {
// parse response
this._Callback();
}
}
Ok, while I was putting together this sample code, I realised I already solved this with the api caller worker! 🙂 Got to have more sleep.
AfterQuestion: does this architectural approach seems really wrong? Please advice a better one, or a pattern that suits the system where concurrent asynchronous API calls are used.
If you store cbYes and cbNo as member variables inside B. You can call them like normal functions:
Instead of using callbacks like this you can use the event system to achieve the same result. You can create custom events and dispatch the yes/no event.