Filtering a set of objects for display in Ember.js

A pretty standard use case in web development in to display a list of objects filtered by some kind of criteria. This is really easy to do in Ember.js using the filterProperty function from the Ember.Enumerable mixin, which is mixed into the DS.RecordArray and DS.AdapterPopulatedRecordArray classes. These are the array implementations returned by DS.Model.find() and DS.Model.find({key: value}) respectively, as well as DS.hasMany associations.

So lets assume that you have a CategoriesRoute which retrieves the array of all Categories from the server in the model function. Something like:

A simplistic implementation would simply list all of the categories on the page, but we would like to filter the result set in the browser based on the name of the category. Our handlebars template for these two cases would look like:

Now we need to add the function to the controller which will sort the categories. We have decided that we want to filter by the name of the category. 

We are calling the filterProperty function on the model for this controller, which was set to App.Category.find() by the route. We are passing in two parameters:

  1. The name of the property on the App.Category object that we are going to filter against, we are filtering against the nameLowerCase property.
  2. The actual value to filter against. Any App.Category instances with a nameLowerCase property matching the filter string will be part of the filtered results. 

In addition we have defined the filteredCategories function to be a property of the App.Categories controller. Since it is observing ‘model.@each.nameLowerCase’, this filtered result set will be re-evaluated everytime the lowerCaseName of an App.Category in the controller model changes.

However we have one complication. Our App.Category models only have a name property, which can be a mix of uppercase or lowercase, so we define a nameLowerCase property on the App.Category model which we can filter against. Note that you filter against any property of an Ember.Object or DS.Model..

 

 

 

 

About these ads
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

3 Responses to Filtering a set of objects for display in Ember.js

  1. Pingback: Filtering a set of objects for display in Ember...

  2. Pingback: By: Filtering a set of objects for display in E...

  3. Pingback: By: By: Filtering a set of objects for display ...

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s