添加新模型后渲染

Render after adding a new model

我在服务器上有一些模型已经引导。他们正在成功获取和呈现。但是当我保存一个新模型时,我无法渲染它。当我重新加载页面时 - 一切正常:渲染了新添加的模型。如何让它即时呈现(不刷新页面)?

这是我的 ListView

var GroupView = Backbone.View.extend({
    tagName: 'ul',

    initialize: function () {
        this.collection = new StudentsCollection();
        // this.collection.on('add', this.render, this);
        this.collection.on('update', this.render, this);
        // this.collection.on('reset', this.render, this);
        this.collection.fetch({
            success: function () {
                console.log('success!');
            },
            error: function (collection, response, options) {
                console.log(options);
            }
        });
    },

    render: function () {
        // this.$el.empty();
        var self = this;

        this.collection.each(function (student) {
            var studentView = new StudentView({
                model: student
            });
            self.$el.append(studentView.render().el);
        });
        $('.container').append(this.$el);
    }
});

我在一个集合上尝试了 'add' 事件,但这只是一切的两倍。有什么想法吗?

在集合上使用 add 是正确的做法,因为您想在添加模型时做一些事情。你看到所有东西加倍的原因(我怀疑除了最近添加的那个)是因为你的渲染功能只是附加到 $el.

Backbone 不会在渲染前清除现有视图,您必须决定使用什么策略。

最简单的解决方案是简单地添加 this.$el.empty()render 的开头。我不建议这样做,因为它会在您每次添加模型时重新渲染整个内容。

更好的解决方案是创建一个函数,仅向现有视图添加一个视图并在 add 上触发该视图。

有点像下面

initialize: function() {
    ...
    this.collection.on('add', this.addStudentView, this);
    ...
}

addStudentView: function(model) {
    var studentView = new StudentView({
        model: model
    });
    this.$el.append(studentView.render().el);
}