Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone click event not firing on dynamic view

I have a backbone view that creates a new div for each model that is passed into it. However, I cannot get any sort of events to fire (click a.change-status) on the view and I assume it's because the elements inside of it are also generated from a template. Please let me know if there's some way around this.

var videoDivView  = Backbone.View.extend({
el: '<div class="vendor-video" />',
initialize: function(){
    _.bindAll(this);
    this.render();
    this.model.on('change:published', this.enableSaveButton);
},
events: {
    'click a.change-status'     : 'changeVideoStatus'
},
template: video_tmpl,
render: function(){
    this.$el.attr("id", 'video-'+this.model.id);
    this.$el.html(this.template(this.model.toJSON()));
    this.$el.data('status', video_statuses[this.model.get('published')]);
},
changeVideoStatus: function(e) {
    console.log(this.model);
    return false;   
}, 
enableSaveButton: function() {
    $('#save-changes').removeClass('disabled').removeAttr('disabled');
}
});

an example template would look like:

<script id="single-video-tmpl" type="text/x-jquery-tmpl">
<div>
    <div class="video-info">
        <span class="video-title"><%=video_title%></span>
        <div class="bottom-info">
            <a href="#<%=id%>" class="change-status"></a>
        </div>
    </div>

</div>
</script>
like image 589
Drew Bartlett Avatar asked Aug 28 '13 00:08

Drew Bartlett


1 Answers

Try a this.delegateEvents() after you render the new content.

like image 162
kikuchiyo Avatar answered Nov 15 '22 18:11

kikuchiyo