Ember-Data:访问侧载资源列表?

时间:2013-11-17 05:04:28

标签: ember.js ember-data

我有一些在/documents路径中具有此结构的JSON(ID是UUID):

{
   "tags": [
      {
         "id": "a33fc396-2428-11e3-8eeb-0800270f33f4",
         "name": "test"
      }
      <more tags not shown>
   ],
   "documents": [
      {
         "id": "c41460fa-2427-11e3-8702-0800270f33f4",
         "name": "file.txt",
         "tag_ids": [
            "a33fc396-2428-11e3-8eeb-0800270f33f4"
         ]
      }
      <more documents not shown>
   ]
}

我们看到Tag资源是侧载的。我正在使用ember-data来使用这些路径加载JSON:

App.Router.reopen
  location: 'history'
  rootURL: '/'

App.Router.map ->
  @resource 'documents', ->

App.DocumentsRoute = Ember.Route.extend
  model: ->
    @get('store').findAll('document')

和模特:

App.Document = DS.Model.extend
  name: DS.attr('string')
  tags: DS.hasMany('tag')

App.Tag = DS.Model.extend
  name: DS.attr('string')

这很好用;我可以通过模板中的把手{{#each}}块访问所有文档,我可以验证我是否可以访问属于给定单个文档的所有标记

但是,我还希望能够在同一模板中访问所有标签的列表,而无需进入每个文档。它应该不难,因为它存在于JSON中,作为侧载资源,对吧?除了我无法弄清楚如何做到这一点。我已经在控制台中键入了各种各样的东西,看它是否属于控制器中的一个属性,而且我没有找到任何有希望的东西。我猜我需要加载它并将其设置为我的控制器中的某些东西,但我不知道如何编写它。为了能够编写类似的内容,我需要添加到代码中?

{{#each tags}}
  Name: {{name}} <--- should print "test"
{{/each}}

任何想法都表示赞赏!

1 个答案:

答案 0 :(得分:4)

因为您已经加载了所有代码,并且您不想向/tags发送另一个请求。您可以使用store.all('tags')来获取已加载的代码:

App.DocumentsRoute = Ember.Route.extend({
    model: function() {
        var store = this.store;
        return store.findAll('document').then(function(documents) {
            // return an object with documents and tags, to be able to use both in the template
            return {
                documents: documents,
                tags: store.all('tag') // to access all tags loaded in the payload we can just use store.all, so no additional request will be sent
            }
        });        
    }
});

在你的模板中:

{{#each documents}}
  {{#each tags}}
    Tags of that document
  {{/each}}
{{/each}}

{{#each tags}}
  All tags available
{{/each}}

你可以在那个小提琴http://jsfiddle.net/marciojunior/v4aZj/

中看到这一点

<强>观察

在您的有效负载中,您tag_ids只需使用ActiveModelAdapter开箱即用,如果您使用的是RESTAdapter,则需要更改为tags