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!
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:
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.
Although the above should be avoided.