问题描述
我想加载一个完整的集合,然后只是剥离记录,以便一次使用一个模型,而不必每次都向服务器往返。
I would like to load an entire collection and then just peel off records to use as models one at a time, without doing a roundtrip to the server every time.
我已经弄清楚如何使用Ember.Deferred退回承诺,但是我无法在合适的时间得到承诺来解决。以下代码只是输出找到0:
I've figured out how to use Ember.Deferred to return a promise, but I can't get the promise to resolve at the right time. The following code just outputs "Found 0" ever time:
App.PersonRoute = Ember.Route.extend({
model: function(params) {
var name = "Erik";
var promise = Ember.Deferred.create();
App.people = App.Person.find();
App.people.then(function() {
console.log('Found ' + App.people.get('length'));
var person = App.people.findProperty('name', name)
promise.resolve(person);
});
return promise;
}
});
如果我将then()的正文包装在setTimeout中,并使其等待几秒钟,一切都很好。
If I wrap the body of the then() in a setTimeout, and make it wait a couple seconds, everything works great.
有没有另外一个可以以某种方式绑定的事件?我尝试过App.people.on('isLoaded'),但是它是永远是真的。
Is there another event I can somehow bind to? I tried App.people.on('isLoaded'), but isLoaded is always true.
谢谢!
推荐答案
确实有一个你可以听的事件,那就是 didLoad
。
Indeed there is an event you can listen to and that is didLoad
.
至于 isLoaded
对此有很多困惑,请参见,混淆来自于当商店已经完成加载 RecordArray时,设计将
,即使最初空,因为没有可用的本地记录。然后当对服务器的请求返回时,将从后端收到的记录填充 isLoaded
标志设置为true RecordArray
,绑定将开始,您的模板更新。
As for isLoaded
there was a lot of confusion about this, see here for example, the confusion comes from the fact that the isLoaded
flag is set to true by design when the store has finished loading the RecordArray
for the records, even when initially empty because no record was already available locally. Then when the request to the server comes back the RecordArray
will be populated with the records received from the backend, and bindings will kick off and your templates are updated.
如所述:
以上所述是什么使得 didLoad
fire。
Was is stated above is what makes didLoad
fire.
有关更多的模型相关事件,您可以在
For more model related events you can listen to have a look at the guides under model lifecycle
现在,您可以将代码重写为您的设置:
Now to your setup, you could rewrite your code to something like this:
App.PersonRoute = Ember.Route.extend({
model: function(params) {
var name = "Erik";
var promise = Ember.Deferred.create();
App.people = App.Person.find();
App.people.on('didLoad', function() {
console.log('Found ' + App.people.get('length'));
var person = App.people.findProperty('name', name)
promise.resolve(person);
});
return promise;
}
});
希望有帮助。
这篇关于Model.find()。then()在实际加载记录之前触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!