[英]Backbone model parse method (collection / server)
請幫我 :)
我有骨干模型:
var people = Backbone.Model.extend({
...
parse : function() {
return response
}
})
並收集:
var group = Backbone.Collection.extend({
model: people
...
})
通常,我通過調用收集同步方法獲取數據,但有時我調用模型獲取方法。
我的后端返回格式如下:
{code: 0, data: {'1': {name: 'alex'}, '2': {name: 'max'}}}
問題:如果我編寫了用於處理后端答案的模型解析方法-集合同步不起作用(因為服務器答案具有另一種格式),如果我編寫了用於解析的解析方法-則不進行后端處理。
我如何創建通用處理?
我找到了方法,請在解析方法中查看選項,然后使用else / if,但我不喜歡它。
選項1:
使用其他_PeopleBase類會有所幫助嗎?
var _PeopleBase = Backbone.Model.extend({
...
})
var people = _PeopleBase.extend({
...
parse : function() {
return response
}
})
集合:
var group = Backbone.Collection.extend({
model: _PeopleBase
...
parse : function() { //Collection parser
return response
}
})
選項2:如果可能的話,您可以依靠返回的數據來決定如何解析它
parse : function(response, options) {
//Test the response with whichever way you can definitely differentiate them
return response
}
選項3:取決於誰是解析函數的調用者:
parse : function(response, options) {
if (this instanceof People) {
} else {
}
return response
}
希望對您有所幫助!
這是我在我的方法(我有很多嵌套數據,並且必須將現有對象映射到我的視圖以確保我的視圖無需完全刷新就可以更新):
//通過{parse:true},如果Person的嵌套數據也需要解析
parse: function(response, xhr) {
for(var key in this) {
if (key === 'person') {
var embeddedClass,
embeddedData = response[key],
exsiting = this.get(key);
if (existing == null) {
embeddedClass = new Person(embeddedData, {parse: true});
} else {
existing.set(key, existing.parse(embeddedData));
embeddedClass = existing
}
response[key] = embeddedClass;
}
}
return response;
}
然后當新數據到來時,我需要手動再次解析它,我打電話
this.set(this.parse(response));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.