How to call one controller function from another controller function in Lightning?

  • If I have two functions foo() and bar() in my Lightning component controller, how can I call one function directly from another function, without having to queue it up through $A?

    Here's a sample controller setup:

    ({
        bar : function(component, event, helper) {
            // Do something cool
        },
        foo : function(component, event, helper) {
            // How do I call bar() from here?
        }
    })
    
  • I think that the better approach would be to try to extract whatever it is that you need to call in that controller function into the helper and call the helper. The helpers exist to enable sharing code within a component. Do you have a use case where that wouldn't work?

    Just for fun, inspecting the action object the following would work:

    var action = component.get("c.bar");
    action.$meth$();
    

    Obviously don't do that! :)

    Thanks, Peter. This may very well be the right approach. However, it just seemed cumbersome to me, that if I wanted to reuse code across functions, I would always have to pass `helper` as a parameter. Maybe this is just how it needs to be with Lightning, and I guess I just miss being able to call other static or member methods from another static or member method in Apex.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM