我正在使用 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很简洁但相当不错。请记住以下几点:
- 用于注册事件监听器的方法(即
listenTo
或on
)会改变您提供被调用函数上下文的方式。例如,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 的 CollectionView 和 ItemView 。
关于javascript - 在 Backbone 中渲染集合的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28998845/