Search code examples
backbone.js

How to filter by multiple select options in backbone


Currently what I have is almost working. I'm using the following:

this.collection.reset(jobArray, {silent: true});

var filterDepartment = this.filterDepartment;
var filterCategory = this.filterCategory;
var filterLocation = this.filterLocation;

var filteredResult = this.collection.where({
    department: filterDepartment,
    category: filterCategory,
    location: filterLocation
 });

 this.collection.reset(filteredResult);

This works great if I select a department, a category, and a location. However, if I want it to only filter by department + location, leaving category as the default 'all' value, it should return the filtered/ selected department and location, within all categories. Furthermore, if I select a category, then select "all" instead, it should then only be searching by location.

I have a way to do this but it is a LOT of code, surely there is an easier way?


Solution

  • How about

    this.collection.reset(jobArray, {silent: true});
    
    var filterDepartment = this.filterDepartment;
    var filterCategory = this.filterCategory;
    var filterLocation = this.filterLocation;
    
    var filter = {};
    if (filterDepartment)
        filter['department'] = filterDepartment
    
    if (filterCategory)
        filter['category'] = filterCategory;
    
    if (filterLocation)
        filter['location'] = filterLocation;
    
    console.log(filter); // Dump the filter
    
    var filteredResult = this.collection.where(filter);
    
    this.collection.reset(filteredResult);