ember.js – Model.find().then()在实际加载记录之前触发

前端之家收集整理的这篇文章主要介绍了ember.js – Model.find().then()在实际加载记录之前触发前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想加载一个完整的集合,然后剥离记录,一次一个地用作模型,而不是每次都进行到服务器的往返.

我已经想出如何使用Ember.Deferred返回一个承诺,但我无法在合适的时间得到解决的承诺.以下代码输出“找到0”时间:

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中,并让它等待几秒钟,那么一切都很好.

我可以以某种方式绑定到另一个事件吗?我尝试了App.people.on(‘isLoaded’),但isLoaded始终是真的.

谢谢!

解决方法

Is there another event I can somehow bind to?

确实有一个你可以听的事件,那就是doLoad.

I tried App.people.on(‘isLoaded’),but isLoaded is always true.

至于isLoaded,对此有很多困惑,例如参见here,混淆来自于当商店完成为记录加载RecordArray时isLoaded标志被设计为true的事实,即使最初是空的,因为当地没有记录.然后,当对服务器的请求返回时,RecordArray将填充从后端接收的记录,绑定将启动,模板将更新.

guides所述:

A record that is both loaded and clean means that is has received information about its attributes and relationships from the server,and no changes have been made locally on the client.

上面说的是什么使didLoad火.

有关更多模型相关事件,您可以聆听查看model lifecycle下的指南

现在进行设置,您可以将代码重写为以下内容

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;
  }
});

希望能帮助到你.

猜你在找的JavaScript相关文章