Event binding on underscore/lodash templates

1.7k Views Asked by At

I have an example lodash template inside a jquery plugin as shown below:

<div>
    <% _.forEach(circle, function(circle, idx){%>
          <a class='circle'> <%- circle.circleName %> </a>
    <%})%>
</div>

I would like to add click event handler to the a tag. Currently, I am doing the below after rendering the above template on the DOM:

$(".cricle").each(function(circle){
    $(circle).click(function(elm){
        console.log("Clicked: ", elm)
    })
})

So, Is there a way in lodash or jquery through which I would not have to do the shown repetitive work.

Thanks!

1

There are 1 best solutions below

1
On BEST ANSWER

First of all you don't need to iterate through matched elements to bind the same event handler to a collection of elements. The following should do fine:

$('.circle').on('click', function(elm) { console.log('Clicked: ', eld); });

I'm pretty sure lodash does not provide a special way to bind event handlers inside templates.

You may use vanilla JavaScript to define inline event handlers on your elements.

<a class='circle' onclick="console.log('Clicked: ', this">
  <%- circle.circleName %>
</a>

Although the above should be avoided.