【问题标题】:How to make Ember.js load RESTAdapter data before showing view?如何让 Ember.js 在显示视图之前加载 RESTAdapter 数据?
【发布时间】:2013-08-01 08:24:25
【问题描述】:

我有一个带有 RestAdapter 的应用程序,它从服务器获取正确的数据:

App.AFile= DS.Model.extend({
  name: DS.attr( 'string' ),
...

App.Store = DS.Store.extend({
  revision: 13,
  adapter: DS.RESTAdapter.extend({url: "myapi"})
});

还有这样的地图:

App.Router.map(function() {
  this.resource('allfiles', { path: '/allfiles' });
  this.resource('onefile', {path: '/onefile/:onefile_id' });

和这样定义的路由:

App.allfilesRoute = Ember.Route.extend({
  model: function()
  {
      return App.AFile.find();
  }
});

App.onefileRoute = Ember.Route.extend({
  model : function(params)
  {
      return App.AFile.find(params.onefile_id);
  }
});

还有那些模板:

 <script type="text/x-handlebars" data-template-name="allfiles">
 {{#each controller}}
    {{#linkTo onefile this}}open{{/linkTo}}
 {{/each}}
 </script>

 <script type="text/x-handlebars" data-template-name="onefile">
   {{name}}
 </script>

它的工作原理是这样的:用户打开应用程序并显示所有文件模板,其中包含一个名为 open 的链接。该链接会打开一个名为 onefile 的模板并将 onefile_id 传递给它。

当我打开应用程序并单击打开时,它可以工作并显示一个文件的正确名称。 URL 设置为 #/onefile/1,其中 1 是 onefile_id。所以它工作正常。

但是当我刷新页面 (#/onefile/1) 时,不再显示名称。

在我返回 id 之前,我已经检查了 onefileRoute 模型函数中发生的情况,并且 App.AFile 对所有定义的字段都有空值。在应用加载后,这些值会正确填充到 App.AFile 对象中,但不会显示在视图上。

所以看起来 RestAdapter 在视图显示后获取数据。

如何让它发挥作用?

【问题讨论】:

    标签: javascript rest ember.js


    【解决方案1】:
    App.onefileRoute = Ember.Route.extend({
      model : function(params)
      {
          var m = App.AFile.find(params.onefile_id);
          // at this point m might not be resolved, so name could be empty
          return m;
      },
      afterModel: function(model, transition){
          // at this point it should be resolved, what happens here?
          console.log(model.get('name'));
      }
    });
    

    我的猜测是您的端点通过 id 返回模型的错误信息。

    【讨论】:

    • 在aftermodel model.get('name') 仍然返回null
    • 在 Chrome 中,如果您查看网络选项卡,您是否看到呼叫和响应?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多