Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I filter records in the Route or Controller in Ember.js?

Tags:

ember.js

I'm going through the Ember.js course at Code School and they first used the filter method in a controller, explaining that the controller is used to decorate the model. But then in the next section he filtered records in the Route, chaining the method on to 'store.findAll'.

I'm relatively new to Ember so this is confusing. In the first instance, we have an array of products that we want to filter though to retrieve an array of onSale products to post in the index template. We retrieved the model on the Index Route:

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return this.store.findAll('product');
  }
});

Then the Route sends the products to the controller where we can decorate the data and reduce it to only 3 products.

App.IndexController = Ember.ArrayController.extend({
  onSale: function() {
    return this.filterBy('isOnSale').slice(0, 3);
  }.property('@each.isOnSale')
});

I understand this much. But then we created a link to the 'products/onsale' template that will list out all onsale products. We created a ProductsOnsaleRoute where we use modelFor to pull in the parent model from the ProductsRoute but then we go ahead and filter in the Route rather than creating a ProductsOnsaleController and filtering there. Is there an explanation for this?

App.ProductsOnsaleRoute = Ember.Route.extend({
  model: function() {
    return this.modelFor('products').filterBy('isOnSale');
  }
});

I guess my question is...would it be better for me to create a ProductsOnsaleController and filter there?

App.ProductsOnsaleController = Ember.ArrayController.extend({
  sale: function() {
    return this.filterBy('isOnSale');
  }
}):

Thanks for your help!

like image 518
reknirt Avatar asked Feb 28 '14 01:02

reknirt


1 Answers

Coincidentally I was talking about this very topic with my team lead today. He brought up the very valid point that the trouble with filtering at the Route level is that it's not "binding aware".

Suppose you decide to filter on a property that determines if an item should be displayed. If you do the filtering at the controller level, a user action could remove an item from display. If your filtering is done in the setupController of a Route, this is not true; you'd have to revisit the route for the item to be removed.

like image 178
jherdman Avatar answered Jan 02 '23 12:01

jherdman