Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery event inside a underscore.js template

I'm having trouble including javascript code inside an underscore.js template (particularly a jquery .click() event). I've tried many variations of the <% .. %> tags, and here is my latest:

 <script type="text/html" id="eventTemplate">
  <% _.each(words, function(word) { %>
      <a data-role="button" id="eventButton <%= word %>" href="#" data-icon="plus" data-iconpos="right">
          <%= word %>
      </a>
     <% $('#eventButton' + word +').click(function() {
         console.log(word);
        });
     }); %>

Any help will be appreciated. Thanks

like image 876
infrared Avatar asked Aug 13 '26 18:08

infrared


1 Answers

That's not a good idea. The code would be executed during the evaluation of the template, not when (or after) the produced HTML is inserted into the DOM. But you need that to make the jQuery selectors working.

So, separate behaviour from content!

<script type="text/html" id="eventTemplate">
<% _.each(words, function(word) { %>
    <a href="#" data-role="button" class="eventButton" data-word="<%= word %>" data-icon="plus" data-iconpos="right">
        <%= word %>
    </a>
<% }) %>
</script>
// then:
    var html = _.template(eventTemplate, data);
    $(domElement).html(html).on("click", ".eventButton", function(e) {
        console.log($(this).data("word"));
    });
like image 164
Bergi Avatar answered Aug 15 '26 08:08

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!