0
votes

Hi guys i have bunch of images that i want to sort by 'Recent' or 'Popular' or 'Hot'.
For now i have a route which is defined like this:

App.Router.map(function () {
    this.route("browse");
});

I wanted to do something like browse/recent to show the images by recent and browse/popular for the popular but I cant nest routes.

Shall I change my code so instead of the browse route ill have images resource?
And nest into it my filters? so ill have something like images/recent images/popular...
It seems like too many routes, maybe ill have in the future 10 filters does it mean ill have to create 10 different routes & controllers? cant i just use 1 controller and set a logic to filter(with ember-data)?

2

2 Answers

1
votes

You should probably use a noun (images) as a resource name. You can then create multiple routes, each applying different filter on your data (different model hook), but each using the same controller / template. A simplified example:

First, create an images resource, with individual routes for your filters:

App.Router.map(function() {
  this.resource('images', function () {
    this.route('hot');
    this.route('new');
  });
});

Then, create a shared route, which will use hardcoded template and controller. The part with setupController is needed because the default controller will be (probably auto-generated) controller for ImagesNew or ImagesHot. You must take the given model and use it to set up shared ImagesController.

App.ImagesRoute = Ember.Route.extend({
    renderTemplate: function() {
      this.render('images', {
        controller: 'images'
      });
    },
    setupController: function (_, model) {
      this.controllerFor('images').set('content', model);
    }
});

App.ImagesController = Ember.Controller.extend({
  // your shared logic here
});

Finally, you can create filtering routes. Each should inherit the base ImagesRoute and provide its own filtered data in the model hook.

App.ImagesHotRoute = App.ImagesRoute.extend({
    model: function () {
      return this.store.getHotImages();
    }
});

App.ImagesNewRoute = App.ImagesRoute.extend({
    model: function () {
      return this.store.getNewImages();
    }
});

Working jsbin example here.

1
votes

It's a best practice to start with a resource and then nest routes within it.

App.Router.map(function() {
  this.resource('images', { path: '/' }, function() {
    this.route('browse');
    this.route('hottest');
    this.route('popular');
  });
});

As far as creating ten different controllers, that is not necessary. I'd imagine that the route logic will be different (HottestRoute will load the hottest photos, PopularRoute will load the most popular), but the controller logic should be the same. It is probably best to have named controllers, but they can just extend an already defined controlled.

App.ImagesPopularController = ImagesController.extend();