简体   繁体   中英

Backbone view with template not firing events

I'm having some problems with my view handling it's events. They simply don't fire. The view has it's html from a template that looks like this:

<script type="text/template" id="intro-slide-template">
  <div class="slide intro" id="intro-slide">
    <a href="#" class="startpresentation" id="start-btn">
      <%= startpresentation %>
    </a>
  </div>
</script>

So far so good. The view code itself look's like this:

  /* ********* Slide View  *********  */
    window.IntroSlideView = Backbone.View.extend({           
        initialize: function(){             
            this.template = _.template($("#intro-slide-template").html());          
        },  
        render: function(){     
            $(this.el).html(this.template(this.model.toJSON()));             
        },
        events: {
            "click #start-btn": "clickHandler"
        },
        clickHandler: function() {
            console.log("IntroSlideView     ::      clickHandler");
        }           
    });

This is how I render the slide to the main app's view:

/* ********* App View  *********  */
window.AppView = Backbone.View.extend({
    el: $("#content"),
    initialize: function(){
        _.bindAll(this, 'render');      

        //render 
        this.render();
    },
    render: function(){                     
        this.el.innerHTML = "";     
        var slide = this.model.get("currentSlide");
        slide.render();             
        this.el.innerHTML = slide.el.innerHTML;
    }   
});

The view is getting rendered to the screen perfectly, and it works just like it should. But the click event is not firing.

When I inspect the slide view object, I can see that it do haves el object with the right HTML in it, including the button that has to fire a click event.

And when I log the view's events, I see that they are set:

Object
click #start-btn: "clickHandler"
__proto__: Object

Try this pattern

window.AppView = Backbone.View.extend({
  render: function() {
    this.slide = new window.IntroSlideView({ el: this.$(".slide") });

    // ...
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM