我一直在尝试将我的主干.js 应用程序连接到现有的 Codeigniter API。我查看了 github 上的 todos 示例并从那里开始构建。我正在覆盖 findAll 函数,该函数在“读取”时调用,并试图获取页面并将它们返回给 fetch 函数:
findAll: function() { console.log('synch - findAll');
var url = "/folio/get/8";
var data = '';
var postmethod = 'GET';
$.ajax({
url : url,
type : postmethod,
async: false,
data: data,
success: function(response)
{
console.debug("response",response);
console.debug("response.pages", response["pages"]);
return _.values(response["pages"]);
}
});
}
API 返回类似这样的内容 - 通过 console.debug("response", response) 输出:
{
"id": "8",
"facebook_id": "123456789",
"title": "title",
"access_date": null,
"rating_avg": "0",
"pages": [
{
"id": "6",
"picture1": {
"id": "3",
"tag": "1",
"tip": "Crazy",
"facebook_picture_id": "1239102391023"
},
"picture2": "28",
"picture3": "29",
"picture4": null,
"picture5": null,
"picture6": null,
"caption1": "caption 1",
"caption2": "caption 2",
"sequence": "2",
"folio": "8",
"ts": "2012-04-10 15:13:23",
"template": "#page-template-2"
},
{
"id": "5",
"picture1": "24",
"picture2": "25",
"picture3": "26",
"picture4": null,
"picture5": null,
"picture6": null,
"caption1": "caption 1",
"caption2": "caption 2",
"sequence": "4",
"folio": "8",
"ts": "2012-04-10 15:13:23",
"template": "#page-template-2"
}
]
}
但随后 console.debug("response.pages", response["pages"]) 打印出“未定义”。为什么这样做?
提前非常感谢!
- - - - - - - - - - 编辑 - - - - - - - - - - -
感谢您的回答。我可以在模型中进行 ajax 调用的技巧真的很有帮助。问题是我试图将几个页面放入一个 PageList 集合中:
$(function(){
// Page Collection
// ---------------
var PageList = Backbone.Collection.extend({
model: Page,
localStorage: new Store("wickes-backbone"), // this to get hold of my overwritten localstorage file - it is not actually a localStorage
nextOrder: function() {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
comparator: function(page) {
return page.get('order');
}
});
window.Pages = new PageList;
});
所以在我正在调用的 appview 初始化函数中
Pages.fetch();
它填充所有页面并更新视图。我不确定如何在模型本身中做到这一点?