Search code examples
actionscript-3apache-flexadobe

How to call a function in a child component in: a) another child component b) parent component and vice versa?


I have a parent component, say P, which has function, say Pfunc. I also have two child components, say C1 and C2, and their respective function, say C1func and C2func.

How to call any function from any component?


Solution

  • How to call any function from any component?

    From an encapsulation perspective:

    You never should be able to call any function in any component. To "Communicate up" to a parent component, you should make use of event dispatching. To communicate down; you should call a function or set a property. You should never communicate sideways.

    If you want P to execute PFunc, then just execute it:

    this.PFunc();
    

    If you want P to execute C1Func, and C1Func is public, then you can do something like this inside of P:

    C1Instance.C1Func()
    

    If you want P to execute C2Func, and C2Func is public, then you can do something like this inside of P:

    C2Instance.C2Func()
    

    If you want C1, or C2, to call PFunc, then you should dispatch an event like this:

    dispatchEvent(new Event('callPFunc'));
    

    Inside P, there should be an event listener, conceptually like this:

    C1Instance.addEventListener('callPFunc',onCallPFunc);
    
    ....
    // elsewhere in code
    
    protected function onCallPFunc(event:Event):void{
      PFunc();
    }
    

    If you want C1 to call C2Func or C2 to call C1Func, then you're a bit out of luck. The two components at the same hierarchy level should have no direct interaction with each other. The best way to do that is to dispatch an event; listen for it in the parent, and have the parent call back down to the alternate component.