Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emberjs: How to filter by more than one property at once

Below I am filtering by a single property sure, but how do I filter by another one in one go? That is, without providing the user with a drop down containing different search options Example: My search term maybe name, email or age.

var search = this.controllerFor('employees').search; //can be name, email or age

employees = this.get('currentModel').filterProperty('name', search);

The above works fine for updating the master list but I am only able to filter by one property at a time.

//Sample Model
App.Employee = DS.Model.extend({
    email: DS.attr('string'),
    name: DS.attr('string'),
    age: DS.attr('number'),
})

One thought is to re-filter again if the filter results length = 0 and some how merge the results. However, I am not big on that idea and believe Ember may have a better - more elegant way of achieving this.

like image 266
KALBB Avatar asked Mar 09 '13 11:03

KALBB


1 Answers

You can use the filter function to filter more than one property in your model, and even use other properties from controller. For example:

Imagine a model like this:

App.Person = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    fullName: function() {
        return '%@ %@'.fmt(
            this.get('firstName'),
            this.get('lastName')
        );
    }.property('firstName', 'lastName')
});

to filter by multiple properties, let's say you have a controller with a search function similar to this:

...
performSearch: function(searchTerm) {
    return this.get('content').filter(function(person) {
        return person.get('firstName').indexOf(searchTerm) !== -1 ||
               person.get('lastName').indexOf(searchTerm) !== -1;
    });
},
...

This will iterate through the list of contacts in content and apply one or more filters, returning only the model objects that correspond to the filter.

Fiddle: http://jsfiddle.net/schawaska/ABJN7/

like image 151
MilkyWayJoe Avatar answered Oct 21 '22 17:10

MilkyWayJoe