1

好吧,所以我现在还很陌生,我Backbone.js遇到了一个似乎很多其他人都遇到过的问题,但我可以让建议的解决方案发挥作用。

长话短说,每当s 集合发生变化时,我有一个ul视图可以将li自身内部的 s 管理为子视图。ul第一次渲染工作正常,Soccer.Teams.Li点击事件将触发。如果集合上发生了addor事件,则“重新渲染”的子视图不再绑定点击事件。changeli

这是有问题的代码:

Backbone.View.prototype.close = function () {
        console.log('closing time!');
        this.undelegateEvents();
        this.remove();
        this.unbind();
        if (this.onClose) {
            this.onClose();
        }
    };
Soccer.Teams.ListView = Backbone.View.extend({
        tagName: 'ul',
        className: 'ui-listview',
        lis: [],
        initialize: function(teams){
            this.teams = teams;
            this.teams.on('add change', this.render, this);
        },
        render: function(){
            while(this.lis.length>0){
                this.lis[0].close();
                this.lis.shift();
            }
            this.$el.empty();
            this.$el.attr('data-role','listview').css('margin','0px').css('width','220px').attr('id','teams-list');
            this.teams.forEach(function(team){
                this.lis.push(new Soccer.Teams.Li(team));
                this.$el.append(this.lis[this.lis.length-1].render().$el);
            }, this);
            $("#teams-list-container").html('').append(this.el);
            this.$el.listview();
            this.delegateEvents();
            return this;
        }
    });

Soccer.Teams.Li = Backbone.View.extend({
        template: compileTemplate('team-li'),
        tagName: 'li',
        initialize: function(team){
            this.team = team;
        },
        events: {
            'click a': 'open'
        },
        open: function(event){
            console.log('here');
            event.preventDefault();
            this.$el.parents('ul').find('.ui-btn-active').removeClass('ui-btn-active');
            this.$el.addClass('ui-btn-active');
            var teamView = new Soccer.TeamView(this.team);
            teamView.render();
        },
        render: function(){
            this.$el.empty();
            this.$el.append(this.template(this.team));
            this.delegateEvents();
            return this;
        }
    });

如您所见,我是unbindingundelegating以及redelegating。看看有什么问题吗?

4

0 回答 0