重新渲染子视图会丢失事件

时间:2013-01-17 12:20:15

标签: backbone.js

我看过this question但是在重新渲染后我仍然无法维护子视图的事件。我试图在这里重新创建我的问题:

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/

在重新渲染视图的示例中,禁用子视图中的click事件。我不确定为什么这不起作用。

1 个答案:

答案 0 :(得分:2)

根据你发布的the link的解释。您只需在this.composer.delegateEvents();empty()来电之间加入append()来电即可。 (Explained in the link

只需将MainView修改为:

即可
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);
    }
});

在这里看一下JSFiddle: http://jsfiddle.net/4qrRa/5/