Luke Vella
Luke Vella

Reputation: 746

Re-rendering subviews loses events

I've had a look at this question but I'm still having trouble maintaining the events of a subview after re-rendering. I tried to recreate my issue here:

var MainView = Backbone.View.extend({
    initialize : function() {
      this.composer = new Composer();
    },
    render : function() {
        this.$el.html(this.composer.render().el);
    }
});

var SubView = Backbone.View.extend({
    tagName: 'li',
    events: {
        "click": "click"
    },

    click: function(){
        console.log( "click!" );
    },

    render: function(){
        this.$el.html( "click me" );
        return this;
    }
});

var Composer = Backbone.View.extend({
    tagName : 'ul',    
    render: function(){
        console.log( "Composer.render" );
        this.$el.empty();
        for (var i = 0; i < 5; i++) {
            var sub = new SubView();
            this.$el.append( sub.render().el );           
        }   
        sub.delegateEvents();
        return this;
    }
});

http://jsfiddle.net/4qrRa/2/

In the example re-rendering the view disables the click event in the subviews. I'm not sure why this doesn't work.

Upvotes: 0

Views: 849

Answers (1)

Amulya Khare
Amulya Khare

Reputation: 7708

Following the explanation from the link you posted. You just need to include a this.composer.delegateEvents(); call in between the empty() and the append() calls. (Explained in the link)

So simply modify your MainView as:

var MainView = Backbone.View.extend({
    initialize: function () {
        this.composer = new Composer();
    },
    render: function () {
        this.$el.empty();
        this.composer.delegateEvents();
        this.$el.append(this.composer.render().el);
    }
});

Take a look at the JSFiddle here: http://jsfiddle.net/4qrRa/5/

Upvotes: 2

Related Questions