在 Backbone 中呈现集合的最佳方法

Best method for rendering collection in Backbone

我正在使用 Backbone 并且我有以下型号和系列

App.Models.Person = Backbone.Model.extend({
});

App.Collections.People = Backbone.Collection.extend({
    model: App.Models.Person,
    url: 'api/people',
});

然而,我正在苦苦挣扎的是呈现此集合的最佳方式。到目前为止,这是我的工作方式,但似乎不是最优雅的解决方案

App.Views.PeopleView = Backbone.View.extend({
    el: $(".people"),

    initialize: function () {
        this.collection = new App.Collections.People();

        //This seems like a bad way to do it?
        var that = this;
        this.collection.fetch({success: function(){
            that.render();
        }});
    },

    render: function () {
        var that = this;
        _.each(this.collection.models, function (item) {
            that.renderPerson(item);
        }, this);
    },

我是 Backbone 的新手,但必须将 this 分配给另一个变量才能在成功函数中使用它,这似乎是一种糟糕的做事方式?任何有关最佳实践的帮助将不胜感激。

如果您的视图应该只呈现集合,您可以将集合发送到模板并在模板中迭代,否则您可以为此目的创建另一个子视图或将集合的各个模型发送到另一个子视图并附加容器,希望对你有帮助。

Backbone 允许您注册您可以响应的事件。当集合与服务器同步时,它总是会触发 sync 事件。您可以选择监听该事件并调用任何给定的方法。例如...

initialize: function () {
    this.collection = new App.Collections.People();
    this.listenTo(this.collection, "sync", this.render);

    // Fetch the initial state of the collection
    this.collection.fetch();
}

... 将设置您的集合,以便每当 sync 发生时它总是调用 this.render()

The docs on Backbone Events 简洁但很好。请记住几件事:

  • 您用来注册事件侦听器的方法(即 listenToon)会改变您提供被调用函数上下文的方式。 listenTo,例如,将自动使用当前上下文; on不会。 This piece of the docs 解释得很好。
  • 如果需要删除视图,则需要断开事件侦听器。最简单的方法是首先使用 listenTo 连接它们;然后在销毁视图时你可以调用 view.stopListening().

对于渲染,有很多关于如何做的建议。通常有一个视图来渲染每个单独的模型是一种方法。您还可以使用 Backbone.Collection#each 迭代模型 控制迭代函数的范围。例如:

render: function() {
    this.collection.each(function(model) {
        var view = new App.Collections.PersonView({ model: model });
        view.render();
        this.$el.append(view.$el);
    }, this);    
}

注意 .each 的第二个参数指定迭代器的范围。 (再一次,看看 the docs on controlling scope. If you'd rather have a framework help out with the rendering, check out Marionette's CollectionView and ItemView.