Skip to content

Instantly share code, notes, and snippets.

@selvagsz
Last active February 25, 2016 10:34
Show Gist options
  • Save selvagsz/d0fda9a5a864648e7444 to your computer and use it in GitHub Desktop.
Save selvagsz/d0fda9a5a864648e7444 to your computer and use it in GitHub Desktop.
Ember CPM for filter-by-query
import Ember from 'ember';
import filterByQuery from 'demo-app/computed-macros/filter-by-query';
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
items: [
{title: 'Annapurna I', location: 'Nepal', continent: 'Asia'},
{title: 'Annapurna II', location: 'Nepal', continent: 'Asia'},
{title: 'Annapurna III', location: 'Nepal', continent: 'Asia'},
{title: 'Eiger', location: 'Switzerland', continent: 'Europe'},
{title: 'Everest', location: 'Nepal', continent: 'Asia'},
{title: 'Gannett', location: 'Wyoming', continent: 'North America'},
{title: 'Denali', location: 'Alaska', continent: 'North America'}
],
filteredItems: filterByQuery('items', 'title', 'query')
});
<h1>Welcome to {{appName}}</h1>
<br>
<br>
{{outlet}}
<br>
<br>
{{input type="text" value=(mut query)}}
<ul>
{{#each filteredItems as |item|}}
{{log item}}
<li>{{item.title}}</li>
{{/each}}
</ul>
const { makeArray, get, getWithDefault, computed, isBlank } = Ember;
// Ember computed macro that does a simple filter with the passed query. No tokenization has been handled.
let filterByQuery = function(itemsKey, fieldKeys, queryKey) {
fieldKeys = makeArray(fieldKeys);
return computed(`${itemsKey}.@each.{${fieldKeys.join(',')}}`, queryKey, function() {
let items = this.get(itemsKey);
let query = this.getWithDefault(queryKey, '').trim().toLowerCase();
if (isBlank(query)) {
return [];
}
return items.filter((item) => {
return fieldKeys.some((fieldKey) => {
return getWithDefault(item, fieldKey, '').toLowerCase().search(query) !== -1;
});
});
});
};
export default filterByQuery;
{
"version": "0.6.0",
"EmberENV": {
"FEATURES": {}
},
"options": {
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "https://cdnjs.cloudflare.com/ajax/libs/ember.js/2.3.1/ember.debug.js",
"ember-data": "https://cdnjs.cloudflare.com/ajax/libs/ember-data.js/2.3.3/ember-data.js",
"ember-template-compiler": "https://cdnjs.cloudflare.com/ajax/libs/ember.js/2.2.0/ember-template-compiler.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment