我试着在我的项目使用的骨干。 但我遇到问题时,试图在此改变骨干的解析方法。 该服务器有发回的数据超过我want.For例如:我要的是:
[{
id: "123",
name: "david"
},{
id: "456",
name: "kevin"
}]
但服务器的结果是:
{
total: 1000,
items:[{
id: "123",
name: "david"
},{
id: "456",
name: "kevin"
}]
}
所以我想在parse方法处理结果,并只返回数组。 我怎样才能做到这一点? 当我尝试我的错误。 我应该怎么做?
在你的骨干模型,定义解析功能,你会喜欢的方式:
Model = Backbone.Model.extend({
parse: function () {
return {
id: this.get("id"),
name: this.get("name")
}
}
});
但是,这将是更好的模型初始化处理,并设置数据,就像这样:
Model = Backbone.Model.extend({
initialize: function (attrs) {
try {
//TODO HERE: test for correct values and throw errors
// set object variables here
this.set({
name: attrs.name,
id: attrs.id
});
} catch (e) {
console.log(e);
}
}
});
没有必要现在覆盖的解析功能。 你知道你的模型处理数据这样是好的,您所设置的变量,它包含的内容。 这避免了无效数据很多错误。
数组中的每一项都应该真正成为一个子模型,这就是我上面写的。 你的父母模型应该是这样的:
Model = Backbone.Model.extend({
initialize: function (items) {
this.subModels = [];
items.forEach(function (item) {
this.subModels.push( new SubModel(item) )
});
}
});
或作为一个集合:
Collection = Backbone.Collection.extend({
model: ItemModel,
});
为了您会通过response.items
从骨干解析文档
Collection = Backbone.Collection.extend({
model: YourModel,
parse: function(response){
return response.items;
}
});