2

I'm trying to add an event listener anytime something inside of a li is clicked, but I'm having issues with it.

Component

<aura:handler name="init" action="{!c.doInit}" value="{!this}" />
<li class="slds-item" aura:id="fullCmp">

</li>

Controller

doInit: function(component, event, helper)
{
    var cmp = component.find("fullCmp");
    alert('cmp = ' + cmp);
    cmp.addEventListener("click", function(){
        alert('Hello World');
    });
}

When I print out the component, I get:

cmp = SecureComponent: markup://aura:html {4:30a}{fullCmp}{key: {“namespace”:”c”}}

My page then throws an error:

cmp.addEventListener is not a function

How can I successfully add an event listener to the li?

2 Answers 2

5

I'm going to assume that you have more than one <li> item for this answer.

You need to run this code in the renderer (or use the newly added event for Summer 17 - we'll use the renderer for now as production code does not support this yet.

Helper:

addListeners : function (component){
  var cmp = component.find("fullCmp");
  cmp.forEach(function(item){

      item.getElement().addEventListener("click", function(){
        alert('Hello World');
      });
  });        
}

Renderer:

afterRender: function (component, helper) {
    var afterRend = this.superAfterRender();

    helper.addListeners(component)
    return afterRend;
},

Don't call the code from the controller init function at all - at this point, the dom is not ready and your components have not rendered yet - hence your error.

For the single component version, replace my forEach with your version.

The event for Summer 17 is aura:valueRender

<aura:handler name="render" value="{!this}" action="{!c.onRender}"/>

Ref here:

EDIT Note - if you are going to be doing anything framework specific, you also need to read this answer which follows on from mine - it shows you how to use $A.getCallback with this answer. Here.

3
-3

There is one quick fix for this issue, instead of writing afterRender method you can use events on your HTML i.e onchange event

<li onchange="someAction();"></li>

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .