[英]Backbone - not parse each model in collection after fetch
如何在集合提取中阻止模型的解析功能?
$(function() {
var Task = Backbone.Model.extend({
url : function() {
return this.urlRoot + this.id;
},
urlRoot: 'index.php?c=light&a=list_tasks_bb&ajax=true&task=',
parse: function (response, options) {
console.log(options);
console.log(response);
return response;
}
});
var TaskList = Backbone.Collection.extend({
model: Task,
url: 'index.php?c=light&a=list_tasks_bb&ajax=true',
initialize: function () {
},
parse: function (response, options) {
return response.tasks;
}
});
var Light = Backbone.Router.extend({
el: $('#light'),
routes: {
"tasks/:id": "taskAction",
"*page": "defaultAction",
},
initialize: function () {
_this = this;
this.tasks = new TaskList();
this.users = new UserList();
},
taskAction: function(id) {
this.task = new Task({id: id});
$.when (
this.task.fetch()
).then(function(zzz) {
new TaskView({model: _this.task}).render();
});
},
defaultAction: function(page) {
$.when (
this.tasks.fetch(),
this.users.fetch()
).then (function() {
new TaskListView({collection: _this.tasks}).render();
});
}
});
});
我有一個模型和一個集合,我通過ajax fetch獲得。 我沒有機會改變后端,所以任務列表的json結構是:
"contents": {},
"current": false,
"errorCode": 0,
"errorMessage": "",
"u": 4,
"tasks": [{
"id": "12250",
"t": "ZZZ",
"cid": "24",
"c": "2013-08-22 11:36:32",
"dd": "02.09.2013",
"sd": "02.09.2013",
"pr": "300",
"pid": "0",
"atid": "1:4",
"s": 0,
"dl": ""
}, {
"id": "12307",
"t": "ZZZ",
"cid": "42",
"c": "2013-08-28 11:14:44",
"dd": "05.09.2013",
"sd": "28.08.2013",
"pr": "200",
"pid": "0",
"atid": "1:4",
"s": 0,
"dl": ""
}, {
"id": "12326",
"t": "ZZZ",
"cid": "2",
"c": "2013-08-29 09:55:34",
"dd": "31.08.2013",
"sd": "29.08.2013",
"pr": "200",
"pid": "0",
"atid": "1:4",
"s": 0,
"dl": ""
}],
"events": []
這就是我使用parse進行收集的原因。 在這一步中,一切都很好。 單個任務的JSON結構是:
"contents": {},
"current": false,
"errorCode": 0,
"errorMessage": "",
"u": 4,
"tasks": [{
"id": "12250",
"t": "ZZZZ",
"cid": "24",
"c": "2013-08-22 11:36:32",
"dd": "02.09.2013",
"sd": "02.09.2013",
"pr": "300",
"pid": "0",
"atid": "1:4",
"text": "XXXXX",
"s": 0,
"dl": ""
}],
"comments": [{
"id": "48178",
"text": "CCCC",
"cid": "4",
"con": "23.08.2013"
}],
"events": []
所以我需要再次解析“task.fetch()”之后的獲取單個任務。 在我在模型中添加解析函數之后它工作正常,直到我開始獲取集合,因為在收集解析后我已經有了正確的模型數據,但模型再次為每個模型解析回調。
我是否有正確的方法來解決這個問題或者更好的方法是嘗試更改后端?
PS當然,我可以這樣做:
if(response.tasks) {
return response.tasks[0];
} else {
return response;
}
但我認為這不是正確的解決方案。
在創建用於插入集合的模型時 ,Backbone將未來集合作為選項傳遞給模型構造函數,模型構造函數又轉發此選項進行parse
。 您可以檢查此屬性並根據需要中止解析:
var Task = Backbone.Model.extend({
parse : function(response, options){
if (options.collection) return response;
return response.tasks[0];
}
});
var TaskList = Backbone.Collection.extend({
model: Task,
parse : function(response){
return response.tasks;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.