Skip to content

Instantly share code, notes, and snippets.

@MartinMalinda
Last active December 5, 2016 20:52
Show Gist options
  • Save MartinMalinda/30136454b03146bb219ce1eb08f04bc6 to your computer and use it in GitHub Desktop.
Save MartinMalinda/30136454b03146bb219ce1eb08f04bc6 to your computer and use it in GitHub Desktop.
New Twiddle
import Ember from 'ember';
const {computed, on} = Ember;
const getFunctionName = function (fun) {
var ret = fun.toString();
ret = ret.substr('function '.length);
ret = ret.substr(0, ret.indexOf('('));
return ret;
};
const dynamicFilterBy = function(targetSource, sourceName, propertyNameKey, filterByKey){
return on('init', function(){
this[`_filterBy${targetSource}Setter`] = () => {
const cp = computed(`${sourceName}.@each.${this.get(propertyNameKey)}`, filterByKey, function(){
return this.get(sourceName).filterBy(this.get(propertyNameKey), this.get(filterByKey));
});
this.set(targetSource, cp);
};
// replace on function with a computed
this[`_filterBy${targetSource}Setter`]();
this.addObserver(propertyNameKey, this, function(){
// reset computed
this[`_filterBy${targetSource}Setter`]();
});
});
}
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
filterByValue: 'John',
filterByProperty: 'name',
users: [{
id: 1,
name: 'John',
email: '[email protected]',
city: 'NY',
},
{
id: 2,
name: 'Lucy',
email: '[email protected]',
city: 'NY'
},
{
id: 3,
name: 'Oliver',
email: '[email protected]',
city: 'SF'
}],
filteredUsers: dynamicFilterBy('filteredUsers', 'users', 'filterByProperty', 'filterByValue'),
});
<h1>Welcome to {{appName}}</h1>
<br>
<br>
{{outlet}}
FilterValue: {{input value=filterByValue}}
FilterProperty: {{input value=filterByProperty}}
<pre>
{{#each filteredUsers as |user|}}
{{user.id}} / {{user.name}} / {{user.email}} / {{user.city}}
{{/each}}
</pre>
<br>
<br>
{
"version": "0.10.6",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.9.0",
"ember-data": "2.9.0",
"ember-template-compiler": "2.9.0",
"ember-testing": "2.9.0"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment