在Backbone中渲染集合的最佳方法

时间:2015-03-11 22:47:10

标签: javascript backbone.js backbone-collections

我使用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分配给另一个变量,我在成功函数中使用它似乎是一种糟糕的做事方式?任何有关最佳实践的帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

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();
}

...会设置您的收藏集,以便在this.render()出现时始终致电sync

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。如果您想要一个框架帮助渲染,请查看Marionette的CollectionViewItemView

答案 1 :(得分:0)

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