handling jQuery onClick event on handlebars

26,752

Solution 1

You have to refresh your Jquery listeners AFTER the insertion of nodes into your DOM HTML.

var source   = "<li><a href="{{uri}}">{{label}}</a></li>";
var template = Handlebars.compile(source);
var context = {"uri":"http://example.com", "label":"my label"};
$("ul").append( template(context) );

// add your JQuery event listeners
$("li").click(function(){ alert("success"); });

Solution 2

there is no need to reattach the event handler on every dynamic DOM update if you're defining them at document level:

$(document).on('click','li',function(){
   alert( 'success' );
});

Hope this helps! :-)

Share:
26,752
Hal
Author by

Hal

OMG its full of stars!

Updated on July 09, 2022

Comments

  • Hal
    Hal almost 2 years

    I would like to set up a simple jQuery onClick event to make the UI dynamic on a handlebars template. I was wondering to addClass() after a specific click.

    consider the HTML (generated by handlebars)

      {{#if hasButton}}
          <div id="container">      
              <button type="submit" class="myButton">Click me!</button>
          </div>
      {{/if}}
    

    i.e: After a click within a button, its container will receive a loading class that will create the interaction using CSS.

    $(".myButton").on("click", function(event){
            $(this).parent().addClass("loading");
    });
    

    This code should goes on my handlebars-template or should I rewrite it into a specific helper for it? Is there any examples that could be provided so I can study it then develop something similar?

    Thanks in advance!

  • Hal
    Hal almost 11 years
    The problem is that the event isn't being triggered because adding that jQuery simply do not works (this code actually goes on handlebars template not an external js). (btw i changed from prev() to parent() for better code readability)
  • Ryan Walton
    Ryan Walton almost 9 years
    Word. Do it this way. But I like to narrow as much as possible by substituting 'document' for the closest renderable node, like the div you rendered the handlebar template in.