我有一个主干集合,我正在尝试在 View 中渲染它。 JSON 数据似乎是正确的,但我无法从 View 中访问这些值。
这是基本集合:
define(['backbone', 'BaseModel'], function(Backbone, BaseModel) {
var BaseCollection = Backbone.Collection.extend({
model: BaseModel,
url: "/collection/get?json=true",
initialize: function() {}
});
return BaseCollection;
});
这是 View :
define(['backbone', 'BaseCollection'], function(Backbone, BaseCollection) {
var BaseView = Backbone.View.extend({
el: $('#baseContainer'),
template: _.template($('#baseTemplate').html()),
initialize: function() {
_.bindAll(this);
this.collection = new BaseCollection();
this.collection.bind('all', this.render, this);
this.collection.fetch();
},
render: function() {
//This returns 3 objects which is correct based on the JSON data being returned from the server
console.log(this.collection.toJSON());
var html = this.template(this.collection.toJSON());
this.$el.html(html);
return this;
},
});
return BaseView;
});
我认为我需要为集合中的每个模型迭代 this.render
。但是,我不确定,因为在完成所有迭代之前它不应该“渲染”。
任何建议都会很棒!谢谢!
最佳答案
您需要让模板通过名称访问模型。当你这样做时:
var html = this.template(this.collection.toJSON());
您最终将一个数组传递给 template
函数,该函数通常需要一个上下文对象(名称/值对)。试试这个:
var html = this.template({collection: this.collection});
然后在模板中,您可以使用collection.each
迭代器函数或任何用于迭代/过滤/映射/等的下划线实用方法来迭代它们。我还建议在为您的模板提供对集合的访问权限时不要使用 toJSON,因为它会使您的数据变得更加愚蠢且难以使用。 toJSON
最好在发出 HTTP 请求时使用。
关于javascript - Backbone.js 在 View 中渲染集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11233095/