[SalesForce] Adding onclick to dynamically created button

I have a component that dynamically creates buttons which, when clicked, apply filters and then re-query the back end for data.

While I can assign onclick events to each button, I can't find a way to call a helper function.

I have only had success in using pure Javascript to assign

myButton.onclick = function(){alert('this works');};

but the code needs to pass parameters to the back end and then process and display the results in the DOM, so I really need to be able to call a helper function.

I saw an article saying someone was able to call a helper function, but this doesn't work when onclick is assigned dynamically. I have tried helper.functionToCall(cmp), this.functionToCall(cmp), this.helper.functionToCall(cmp), functionToCall(cmp) and many other things.

Is there a way to do this?

Best Answer

I just did something like this the other day. Not sure if it meets all your needs but it at least illustrates the concept

Component Controller

({
doinit: function(component,event,helper){
    <iframe name="pc-frame" src="{!v.iframe-url}" style="width: 100%;height: 770px; border: none;" scrolling="true"/>

        $A.createComponent(
            "aura:html",
             { 
                 tag: "iframe",
                 HTMLAttributes:{
                     "id": "pc-frame",
                     "src": tmp, 
                     "scrolling" : "true",
                     "onload" : component.getReference("c.handlerFunction") //You can change to onclick if your html element supports it 
                 },
             }
                function(compo){
                    var container = component.find("container");
                    if (container.isValid()) {
                        var body = container.get("v.body");
                        body.push(compo);
                        container.set("v.body", body);
                    }
                }
        );

},

handlerFunction : function(component, event,helper){

    console.log('something');

}

)}