簡體   English   中英

如何在沒有ember-data的情況下檢索模型?

[英]How to retrieve models without ember-data?

我有一個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.
  }
});

我發現.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-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能夠解決這些問題,因為它已經成熟,而且我知道他們一直在努力工作,以便更換適配器和序列化器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM