title: Backbone.js: Binding event to template button
body: <p>I'm building an application with Backbone.js where a list of items and a placeholder "new" item are displayed. The container is a view that holds all the sub-views and renders them.</p>
  
  <p>I have searched for some time now but can't get it to work.
  The problem is that the "Add" button in the template is not firing the event. I guess it's because of the rendering taking place at a later point in time and so the event is not assigned. Reading other posts this should be taken care of by Backbone.js but it doesn't seem that way. Adding a jQuery event handler after <code>render()</code> does the job but I think that cannot be the solution.</p>
  
  <p>Here's the relevant code of the view:</p>
  
  <pre><code>template: _.template($("#template-time-new").html()),
  events: {
    'click #btn-new-time': 'onButtonNewClick'
  },
  render: function() {
    this.$el.html(this.template());
  
    return this;
  },
  
  onButtonNewClick: function() {
    return false; // in this case: prevent page reload
  }
  </code></pre>
  
  <p>My template (jade):</p>
  
  <pre><code>script(type="text/template", id="template-time-new").
  &lt;h3&gt;
    &lt;label for="new-time-name" class="muted"&gt;Name:&lt;/label&gt;
    &lt;input id="new-time-name" type="text"&gt;
  &lt;/h3&gt;
  &lt;div class="time-inner"&gt;
    &lt;form class="form-horizontal"&gt;
      &lt;label for="new-time-start" class="muted"&gt;From:&lt;/label&gt;
      &lt;input id="new-time-start" type="datetime-local"&gt;
  
      &lt;label for="new-time-end" class="muted"&gt;to&lt;/label&gt; 
      &lt;input id="new-time-end" type="datetime-local"&gt;
  
      &lt;button class="btn" id="btn-new-time"&gt;
        Add
      &lt;/button&gt;
    &lt;/form&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p><b>EDIT:</b></p>
  
  <p>Here's the code from the parent view:</p>
  
  <pre><code>initialize: function() {
    this.newView = new TimeSpanNewView; // &lt;---- the view that is not really working
  
    this.render();
  
    // bind event handlers
    this.collection.on('all', this.render, this);
    // fetch data
    this.collection.fetch();
  },
  
  render: function() {
    var self = this;
  
    self.$el.empty();
  
    if ( self.collection.length &gt; 0 ) {
      self.collection.each(function(timespan) {
        var subView = new TimeSpanView({ // sub views for the items, everything fine here
          model: timespan
        });
  
        subView.render()
        self.$el.append(subView.el);
      });
    } else {
      self.$el.text("Nothing found.");
    }
  
    self.$el.append(self.newView.render().el);
  
    return self;
  }
  </code></pre>