【问题标题】:How to retrieve models without ember-data?如何在没有 ember-data 的情况下检索模型?
【发布时间】:2013-01-04 17:13:56
【问题描述】:

我有一个不适合 Ember-Data 的 Rest Adapter 的 API。大约有 3 个模型,因此我决定使用来自 jQuery 的普通旧 $.ajax。在找到一种如何检索模型并将它们以正确的方式传递给控制器​​的方法时,我大吃一惊。

考虑以下指南中的示例:

App.Router.map(function(match) {
  match('/posts').to('posts');
});

App.PostsRoute = Ember.Route.extend({
  model: function() {
    return App.Post.findAll(); // Just renamed to .findAll.
  }
});

我发现 .findAll 方法必须返回一个 E.ArrayProxy 的实例,否则不可能做这样的事情:

{{#if content}}
  ...
{{else}}
  <strong>Nothing to display</strong>
{{/if}}

我的实现看起来是这样的:

App.Post.reopenClass({
  findAll: function() {
    var result = Ember.ArrayProxy.create({content: []});

    $.getJSON('/posts', function(data) {
      $.each(data, function(i, row) {
        result.pushObject(App.Post.create(row));
      });
    });

    return result;
  }
});

对此我很满意,但我无法想象如何处理单个对象。

App.PostsRoute = Ember.Route.extend({
  model: function(params) {
    return App.Post.find(params.post_id);
  }
});

// This will not work for me. Controller's content property will alway be null.
App.Post.reopenClass({
  find: function(postId) {
    var result = null;

    $.getJSON('/' + postId, function(data) {
      result = App.Post.create(data);
    });

    return result;
  }
});

解决办法是什么?

我是否应该返回带有空内容的虚拟 Ember.ObjectProxy 实例,并在内容实际填充了对象后以某种方式让 Ember 知道?什么是黄金之路?

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    您可以只使用一个普通的旧对象,这基本上就是 ember-data 的工作方式。

    App.Post.reopenClass({
      find: function(postId) {
        // Set some default properties here.
        var result = Ember.Object.create({
          isLoaded: false
        });
    
        $.getJSON('/' + postId, function(data) {
          result.setProperties(data);
          result.set('isLoaded', true);
        });
    
        return result;
      }
    });
    

    这是黄金之路吗?可能不是,您越深入 Ember,您就越想要 ember-data 所承诺的丰富功能集。几个月前,我编写了自己的框架。与 ember-data 相比很糟糕,但它不需要根元素、侧载数据、下划线名称和支持的嵌入关系。我希望 ember-data 能够随着它的成熟解决这些问题,而且我知道他们一直在努力工作,以便更轻松地更换适配器和序列化程序。

    【讨论】:

    • 为什么要使用reopenClass?为什么我声明 App.Post = Ember.Object.extend() 时不能只定义一个查找函数?我试过这个,找不到方法“find”。 “reopenClass”似乎很奇怪
    • 它是类方法而不是实例方法。
    • 这就解释了为什么你使用reopenClass()而不是reopen(),但是我还是不明白为什么你不能在声明App.Post的同时声明它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    相关资源
    最近更新 更多