0

我正在使用 Ember 1.13.2 和 Ember Data 1.13.4。该 API 符合 JSON API 格式 ( http://jsonapi.org/format )。

一个用户有很多项目。在模板中执行{{model.items}}将返回用户的所有项目。

如果我还需要仅显示来自用户的蓝色项目怎么办。我该怎么办?

// Route
import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
     // Executes: http://localhost:3099/api/v1/users/5
    return this.store.findRecord('user', params.user_id);
  }
})

// Template
firstName: {{model.firstName}} - works
<br>items: {{model.items}} - works
<br>blue items: {{model.items}} - what do we do about this?

// app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
  items:        DS.hasMany('item', { async: true }),
  firstName:    DS.attr('string')
});

// app/models/item.js
import DS from 'ember-data';
export default DS.Model.extend({
  user:           DS.belongsTo('user', { async: true }),
  name:           DS.attr('string')
});
4

1 回答 1

2

我误解了原来的问题。似乎您只想获取颜色为蓝色的项目(并避免获取其余项目)。为此,您需要查询服务器,这需要服务器端代码。但是,一旦你完成了服务器端代码,你就可以这样做:

blueItems: Ember.computed('items.@each.color', {
    get() {
        const query = {
            user: this.get('id'),
            color: 'blue'
        };

        return this.get('store').find('item', query);
    }
})

But again, you'll need your server to support querying for that data. (The JSON API states how you need to return the data, but you'll need to implement the query yourself.)


Old answer that filters the items after fetching for display (just for reference):

I would use a computed property:

blueItems: Ember.computed('items.@each.color', {
    get() {
        return this.get('items').filter((item) => {
            return item.get('color') === 'blue';
        });
    }
})

Or the shorthand ;)

blueItems: Ember.computed.filterBy('items', 'color', 'blue')

Not every operation has an Ember shorthand which is why I gave the full example first.

Using computed properties with promises is sometimes tricky, but this computed property should update whenever your items array updates.

于 2015-07-08T16:26:47.247 回答