如何在没有ember-data的情况下检索模型?

Sam*_*mmy 4 ember.js

我有一个API,不适合Ember-Data的Rest Adapter.大约有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.
  }
});
Run Code Online (Sandbox Code Playgroud)

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

{{#if content}}
  ...
{{else}}
  <strong>Nothing to display</strong>
{{/if}}
Run Code Online (Sandbox Code Playgroud)

我的实现看起来如此:

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;
  }
});
Run Code Online (Sandbox Code Playgroud)

我对此非常满意,但我无法想象如何使用单个对象.

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;
  }
});
Run Code Online (Sandbox Code Playgroud)

解决办法是什么?

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

Jas*_*n P 13

你可以只使用一个普通的旧对象,它基本上就是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;
  }
});
Run Code Online (Sandbox Code Playgroud)

这是黄金之路吗?可能不是,你越深入Ember,你就会越想要ember-data承诺的丰富功能.几个月前,我编写了自己的框架.与ember-data相比可怕,但它不需要根元素,侧载数据,强调名称和支持的嵌入式关系.我希望ember-data能够解决这些问题,因为它已经成熟,而且我知道他们一直在努力工作,以便更换适配器和序列化器.

  • 这就解释了为什么你使用reopenClass()而不是reopen(),但我仍然不明白为什么你不能在声明App.Post的同时声明它 (3认同)