【发布时间】:2014-04-01 15:41:34
【问题描述】:
我不试图在视图本身内提供分页。
我的 API 一次返回 500 条记录,如果还有更多,我想自动加载它们。
虽然我现在的解决方案确实提出了请求,但我认为这不是最好的方法,但它确实有效。
App.StructureAdapter = App.ApplicationAdapter.extend({
findHasMany: function(store, record, url) {
// based on the normal `findHasMany` code
var host = Em.get(this, 'host'),
id = Em.get(record, 'id'),
type = record.constructor.typeKey;
if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') {
url = host + url;
}
return this.findWithURL(this.urlPrefix(url, this.buildURL(type, id)), 1);
},
findWithURL: function(url, page) {
var that = this;
var completeUrl = url + "?page=" + page;
var nextPage = page + 1;
return this.ajax(completeUrl, 'GET').then(function(data) {
Em.Logger.log("calling then");
if (data.structures.length > 0){
that.findWithURL(url, nextPage);
}
return data;
});
}
});
我的问题是:
- 有没有更好的方法来自动获取给定请求的所有页面?
- 如何正确确保建立关系。我的
Structure对象上有父/子关系,但实际上只有第一页结果正确关联。
更新
这是我的 json 响应的样子:
{
"structures": [
{
"id": 6536,
"name": "Building",
"updated_at": "2013-05-21T07:14:54-06:00",
"person_id": 6535,
"notes": ""
},
... 499 more objects ...
]
}
它工作正常,它加载第一组就好了。如果需要,我可以在extract/normalize 方法中进行调整。
这是我现在的标准化方法:
App.StructureSerializer = App.ApplicationSerializer.extend({
normalize: function(type, hash, prop) {
// adds the properly link to get children
hash.links = { "children": "structures" };
// change structure_id to parent_id
hash.parent_id = hash.structure_id;
delete hash.structure_id;
return this._super(type, hash, prop);
},
});
同样,链接使它自动知道在哪里寻找有很多关系。
仔细观察,虽然分页页面确实被调用了,但它们根本没有加载到 Ember 数据中。因此,也许如果他们确实加载了,那么关系就会正确建立。
【问题讨论】:
-
你能发布你从服务器收到的json响应吗?你的模型是什么样的?
-
你好@NicholasJohn16,我刚刚添加了 JSON 响应。
-
你在使用ember-data吗?
-
是的,我正在使用 Ember 数据。
-
@RyanJM 我最近也做了一些关于祖先/自加入关系的工作。我没有发现我必须使用 normalize 函数;所以我不确定我的示例应用程序是否对您有帮助,或者您是否使用了我没有想到的更好的方法。这是链接以防万一:github.com/brandonjmckay/ember-ancestry-example
标签: ember.js ember-data