alexhoma
alexhoma

Reputation: 362

Javascript/jQuery listener not working with Underscore.js templates

I'm building a webapp using underscore.js to create the templates. The thing is, when I render a simple template like this:

<div id="container"></div>

<script type="text/template" id="person-template">
    <% person.forEach(function(p) { %>
        <a class="username"> <%= p.username %> </a>
    <% }); %>
</script> 

<script type="text/javascript">
    var container = document.getElementById('container');
    var template = document.getElementById('person-template');
    var renderTemplate = _.template(template.innerHTML);

    container.innerHTML = renderTemplate({
        person: /* ajax object callback response ... */
    });
</script>

If I try to use the person's id to do something with my Javascript. The function isn't working and there is no error on the console. Example:

$('.username').click( function() {
    console.log('hello!');
});

I also tried this, but it doesn't work:

By the way, this is a very simple example, just to explain the problem.

Upvotes: 0

Views: 424

Answers (1)

Cristiam Mercado
Cristiam Mercado

Reputation: 582

Try to use:

$('body').on('click', '.username', function(e) {
    console.log('hello!');
});

This will work for all elements with 'username' class in the body, whether already present or dynamically added later.

Upvotes: 0

Related Questions