0
votes

In a simple, standard ember.js route ...

  this.resource('foo', function () {
      this.route('show');
      this.route('new');
  });

I have a foo template that shows a new button (link to foo/new route) and the foo.bar data of the foo objects (with links to foo/show in a sorted way using the foo controller)

import Ember from 'ember';
export default Ember.Controller.extend({
    sortProperties: [ 'bar:desc' ],
    sortedList: Ember.computed.sort('model', 'sortProperties')
});

The routes foo/show and foo/new do the obvious, nothing special.

I don't need or want a "real" foo/index route, since all my navigation needs are catered for in the foo route and template. Therefore I want to transitionTo from foo/index whenever I enter that route to the first (as in given by the sorting above) foo/show route (or foo\new if there is nothing to show).

I've learned that "the ember way" is to transitionTo out of the route, but never ever out of the controller.

Now, my problem is, that I get access to the unsorted data very easily (it's the model of my parent route, that I can access via modelFor) and I can sort this "manually", but I'd rather use the already sorted data from my parent's controller. Now, I'm at a bit of a loss which hook to use in the route to be sure that my parent route's controller's computed properties are ready - and it doesn't feel right. So, what would be the ember way to do this?

Edit: Non-working example at http://emberjs.jsbin.com/hujoxigami/2/edit?html,js,output ...

1
I've added a jsbin. How do I transition from the FooIndexRoute to the sorted first foo object. I could implement sorting on the model myself, but that doesn't seem idiomatic ember to me; I'd rather re-use the existing sorting definition. But that isn't available at this time.jnfingerle

1 Answers

0
votes

Use the afterModel hook as you mention in one of your comments.

App.FooIndexRoute = Ember.Route.extend({
  afterModel: function(posts, transition) {
    if (posts.get('length') > 0) {
      this.transitionTo('foo.show', posts.get('firstObject'));
    }
}

And there is nothing wrong with sorting your model before you return it from the FooRoute. (Even better if you can receive it already sorted from your API/data storage)

App.FooRoute = Ember.Route.extend({
  model: function() {
    // not fully functional, just illustrative
    return [{id:1, name:"Hans", detail:"german"},
            {id:3, name:"Henri", detail:"french"},
            {id:2, name:"Harry", detail:"english"}].sortBy('name');
  }
});

The sorting properties in the controller remain relevant if you want to provide sorting controls for the user.