[EDIT]已回答[/EDIT]
我刚开始使用Backbone,遇到了一个我无法理解的绊脚石。
我有以下集合,它向我的网站上的JSON-API发送请求,以按类别获取帖子:
Posts.Collections.CategoryPosts = Backbone.Collection.extend({
initialize: function(options) {
this.id = options.id;
var intRegex = /^d+$/;
if(intRegex.test(this.id)) {
this.url_querystring = '?id=' + this.id;
}
else {
this.url_querystring = '?slug=' + this.id;
}
},
url: function() {
return '/api/core/get_category_posts/' + this.url_querystring;
},
model: Posts.Models.CategoryPost
});
现在,这是工作的魅力;但问题是;此返回的JSON实际上是:
{
"status": "ok",
"count": 10,
"count_total": 79,
"pages": 7,
"category": { ... }
"posts": [
{ ... },
{ ... },
...
]
}
因此,当我在集合中使用fetch()
的代码试图将返回分配给各个Post
模型时;它只创建了一个。
如何告诉Backbone应该使用JSON返回中的"post"子对象创建模型?这似乎真的没有太多;或者我不知道该搜索什么?
任何帮助都会很好——最好是朝着正确的方向推动,而不是给出答案。
答案是定义集合的解析函数:
Posts.Collections.CategoryPosts = Backbone.Collection.extend({
initialize: function(options) {
this.id = options.id;
var intRegex = /^d+$/;
if(intRegex.test(this.id)) {
this.url_querystring = '?id=' + this.id;
}
else {
this.url_querystring = '?slug=' + this.id;
}
},
// Make sure you parse the correct JSON object!
parse: function(response) {
return response.posts;
},
url: function() {
return '/api/core/get_category_posts/' + this.url_querystring;
},
model: Posts.Models.CategoryPost
});