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

标签 javascript backbone.js backbone.js-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 分配给另一个变量,以便在 success 函数内部使用它,这似乎是一种不好的做法?任何有关最佳实践的帮助将不胜感激。

最佳答案

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解释得很好。
  • 如果需要删除 View ,则需要断开事件监听器的连接。最简单的方法是首先使用 listenTo 连接它们;然后在销毁 View 时,您只需调用 view.stopListening() 即可。

对于渲染,有很多关于如何进行渲染的建议。通常,拥有渲染每个单独模型的 View 是一种方法。您还可以使用 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

关于javascript - 在 Backbone 中渲染集合的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28998845/

相关文章:

javascript - 动态设置 subview $el 并触发 Backbone 事件

javascript - 使用backbone、underscore、jquery、bootstrap等的Web应用程序

javascript - 带 OR 条件的 Backbone 集合 where 子句

javascript - 如何删除 HTML 元素上的所有事件?

javascript - Jasmine 节点不等待主体完成

javascript - ng-repeat 中的条件 groupBy

javascript - 主干集合和模型url,批量模型集合保存

JavaScript 正则表达式在 IE 6-9 中不起作用 : "Function expected" error

javascript - Backbone.js - 搜索字段 : use only one Item

javascript - 主干在获取时丢失上下文