0

I have the following in my routes

import Ember from 'ember';

export default Ember.Route.extend({
    model: function() {
        return this.store.query('post',{published:true});
    }
});

and a post-viewer component that renders the model. the problem that i am facing with is filter. How can i implement the same without loading the models each time. Currently i am just passing the models in the component and using the following

{{#each posts as |item|}}
{{/each}}

To render the elements. What is the proper way by which lets say i can filter them based on title containing some specific keyword. I tried using this.store.query inside the each loop but that did not work out.

georoot
  • 3,319
  • 1
  • 25
  • 52

2 Answers2

1

If you use this.store.query ember does not cache the result. So probably you should use a .findAll() and then filter the data on the client side. A simple way to do so is inside your model() hook:

return this.store.findAll('post')
  .then(posts => posts.filter(post => get(post, 'published') === true));

This will work because ember-data does cache the result of the findAll() and the filter executes on the client. You can do the same with a computed property. This has some benefits, as, for example, you can filter based on another property. A computed property in your controller for example:

filteredModel: Ember.computed('model.@each.name', 'searchName', {
  get() {
    return get(this, 'model').filter(record => get(record, 'name') === get(this, 'searchName'));
  }
});
Community
  • 1
  • 1
Lux
  • 16,183
  • 3
  • 36
  • 64
0

You can use

https://github.com/DockYard/ember-composable-helpers

and filter/filterBy

filter -Filters an array by a callback.

{{#each (filter (action "isActive") users) as |user|}}
  {{user.name}} is active!
{{/each}}

filter-by Filters an array by a property.

{{#each (filter-by "isActive" true users) as |user|}}
  {{user.name}} is active!
{{/each}}

If you omit the second argument it will test if the property is truthy.

{{#each (filter-by "address" users) as |user|}}
  {{user.name}} has an address specified!
{{/each}}

You can also pass an action as second argument:

{{#each (filter-by "age" (action "olderThan" 18) users) as |user|}}
  {{user.name}} is older than eighteen!
{{/each}}

P.S. Another variant ( pure Ember.js ) - create computed property and iterate over it. And inside computed property filter items

Vasiliy Vanchuk
  • 6,280
  • 2
  • 18
  • 39