如何从返回根参数以及数组JSON API调用创建骨干集合 [英] How to create Backbone Collection from a JSON API call that returns root parameters as well as array
问题描述
Backbone.js的小白在这里。
Backbone.js noob here.
我要创建一个集合,从JSON API外部的我的应用程序。具体来说,从 #1的API。我知道我应该从集合设置URL参数是这样的:
I want to create a collection, from a JSON API external to my application. Specifically, the api from Stackoverflow. I know I should set the url parameter from a collection like this:
App.Collections.Users = Backbone.Collection.extend({
model: User,
url: "http://api.stackoverflow.com/1.1/users/800271;562692?jsonp=?&key=blahblah"
});
问题是,JSON API返回是这样的:
The problem is that the JSON API returns something like:
{
"total": 2,
"users": [
{
"user_id": 800271,
},
{
"user_id": 800272,
}
]
}
}
如何忽略了总的属性?
How do I ignore the "total" attribute?
推荐答案
如果这是你的应用程序的唯一集合,这种API的工作,所有你需要做的就是重写解析
它的方法:
If this is the only collection in your app to work with such api, all you have to do is to override parse
method for it:
App.Collections.Users = Backbone.Collection.extend({
// ...
parse: function(resp, xhr) {
return resp.users
}
})
如果你也有保存您的模型,也许你会需要重写 Backbone.sync
。不要犹豫,请参阅骨干源:这是彻底的注释,易于遵循
If you also have to save your models, maybe you will need to override Backbone.sync
. Don't hesitate to read backbone's source: it's thoroughly annotated and easy to follow.
这篇关于如何从返回根参数以及数组JSON API调用创建骨干集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!