Reputation: 3313
I'm trying to filter the contents of an ArrayController using Ember.computed.filter
based on the input from a text input.
App.IndexController = Ember.ArrayController.extend({
filteredPeople: Ember.computed.filter('model', function(person){
var searchFilter = this.get('searchFilter');
var regex = new RegExp(searchFilter, 'i');
return person.firstName.match(regex);
}),
// this is bound to the value of a text input helper
// I'm just pre-filling the value to show that the filtering does work
searchFilter: 'kris'
});
This works great and filters as expected. However, I'd like it to update anytime the value of searchFilter
is changed (i.e., anytime someone types into the text input). The problem now is that it only updates if a change is made to the model itself or when the controller first loads.
Is there anyway to trigger Ember.computed.filter
to update when searchFilter
updates? I'm using Ember.computed.filter
as it seems much more efficient than a normal computed property which I believe will end up recreating the entire array each time (please let me know if I'm mistaken there). In addition, Ember.compute.filter is just easy to use and very clean!
I created a JSBin with the above setup. When the user types into the textbox I'd like to somehow trigger the Ember.computed.filter
to update itself.
Thank you for your time and any assistance.
Upvotes: 2
Views: 4631
Reputation: 852
Maybe too easy, but Ember.computed.filter supports dependent keys using .property() so this will work fine:
App.IndexController = Ember.ArrayController.extend({
filteredPeople: Ember.computed.filter('model', function(person){
var searchFilter = this.get('searchFilter');
var regex = new RegExp(searchFilter, 'i');
return person.firstName.match(regex);
}).property('model','searchFilter'),
searchFilter: 'kris' //this is bound to the value of a text input helper
});
jsbin: http://emberjs.jsbin.com/tefes/1/edit
Upvotes: 9
Reputation: 3591
I'm not sure how you would do this using the Ember.computed.filter
.
It would be very easy to implement using the Ember.Array.filter
method and a computed propety:
searchFilter: 'kris',
filteredPeople : function(){
var content = this.get('content'),
searchFilter = this.get('searchFilter'),
regex = new RegExp(searchFilter, 'i');
return content.filter(function(person){
return person.get('firstName').match(regex);
});
}.property('content.@each', 'searchFilter')
filteredPeople
will now be re-computed every time something changes in the content
array or when the searchFilter
changes value.
JSBin: http://emberjs.jsbin.com/pitefica/6/edit
Upvotes: 0