Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember - Automatically redirect to firstObject

I'd like an Ember path /clinic/1 to automatically redirect to show the first doctor: /clinic/1/doctor/1.

Each clinic has many doctors.

Unfortunately if I use this code:

var doctor = clinicController.get('content.doctors.firstObject');
router.transitionTo('clinic.doctor.index', doctor);

... it does not work, as content.doctors.length is still 0 when this code runs in app_router.js.

Any ideas?

like image 290
Chris Nolet Avatar asked Jan 13 '13 16:01

Chris Nolet


4 Answers

You should be able to do this:

App.DoctorsRoute = Ember.Route.extend({
  model: function() {
    return App.Doctor.find();
  },

  redirect: function() {
    var doctor = this.modelFor('doctors').get('firstObject');
    this.transitionToRoute('doctor', doctor);
  }
});

This will work because:

  • If the model hook returns an object that hasn't loaded yet, the rest of the hooks won't run until the model is fully loaded.
  • If the redirect hook transitions to another route, the rest of the hooks won't run.

Note that as of 2426cb9, you can leave off the implicit .index when transitioning.

like image 128
Yehuda Katz Avatar answered Nov 03 '22 06:11

Yehuda Katz


Redirecting on the Route doesn't work for me in my ember-data based app as the data isn't loaded at the point of redirection, but this does work for me...

In the roles controller I transition to the role route for the firstObject loaded.

Application.RolesController = Ember.ArrayController.extend({

    selectFirstObject: function () {
        if (this.get('content').get('isLoaded')) {
            var role = this.get('firstObject');
            this.transitionToRoute('role', role);
        }
    }.observes('content.isLoaded')

});

HTH, gerry

like image 41
user2553452 Avatar answered Nov 03 '22 05:11

user2553452


As an update, if you don't want to redirect because you have a nested route, you'll want to use conditional redirect based on the intended route.

redirect has two arguments passed to it, the model and the transition object. The transition has the property targetName where you can conditionally redirect based on its value.

redirect: function(model, transition){
  if(transition.targetName ==='doctors.index'){
    this.transitionTo('doctor', model.get('firstObject'));
  }
}
like image 1
Kingpin2k Avatar answered Nov 03 '22 06:11

Kingpin2k


For EmberCLI users, you'd achieve the same by doing the following:

//app/routes/clinics/show.js
import Ember from 'ember';

export default Ember.Route.extend({
  redirect: function(model) {
    var firstDoctor = model.get('doctors.firstObject');
    this.transitionTo('doctor', firstDoctor);
  }
});
like image 1
Constant Meiring Avatar answered Nov 03 '22 05:11

Constant Meiring