嗨,我有一个json文件,看起来像这样:
{
"links_1": [
{
"navn": "somename",
"link": "http://www.domane.com"
},
{
"navn": "somename",
"link": "http://www.domane.com"
},
{
"navn": "somename",
"link": "http://www.domane.com"
}
],
"links_2": [
{
"navn": "someothername",
"link": "http://www.domane.com"
},
{
"navn": "someothername",
"link": "http://www.domane.com"
},
{
"navn": "someothername",
"link": "http://www.domane.com"
}
]
}
然后我上集合课。现在我想创建一个新的集合,它只包含json文件中的links_1数组。以及另一个新集合,它包含json文件中的links_2数组。
我该如何做到这一点?
var col = new Collection( Collection.prototype.parse = function(response){
return response.links_1;
}
因此,为了进一步说明,我希望我的fetch能够获得特定的json数据对象。
var col = new Collection();
col.fetch(links_1); // here i only want to get links_1 json data
var col2 = new Collection();
col2.fetch(links_2); // here i only want to get links_2 json data
任何帮助都会很棒。
您试图覆盖parse
的做法是正确的,只是做得不正确。尝试:
//define a collection class
var Link1Collection = Backbone.Collection.extend({
parse:function(response) {
return response.links_1
}
});
//initialize a new instance of your collection class and fetch
var collection = new Link1Collection();
collection.fetch();
编辑:要逐个实例选择要提取的字段,可以在fetch
选项中传递自定义选项。选项传递给parse
:
//define a collection class
var LinkCollection = Backbone.Collection.extend({
parse:function(response, options) {
return options.parseField ? response[options.parseField] : response;
}
});
//initialize a new instance of your collection class and fetch
var collection = new LinkCollection();
collection.fetch({parseField:'links_1'});