Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting to first item in ArrayController

Tags:

ember.js

I am trying to redirect to the first item in an ArrayController. I have found a few other questions related to this, but none had answers that seemed to work (a lot of changes have been happening so this is understandable).

One particular answer from Yehuda here:

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

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

I 'think' I have recreated this scenario, but I must have done something wrong...

Any insight into what I am doing wrong is greatly appreciated.

Example JSBin here.

like image 605
Robert Jackson Avatar asked Nov 13 '22 09:11

Robert Jackson


1 Answers

The problem here is that your list of models is not yet loaded from the server. Depending on your needs i would recomend using a promis to let the rout wait abit until your model is loaded.

App.DoctorsRoute = Ember.Route.extend({
  model: function() {
    return App.Doctor.find().then(function (list) {
       return list.get('firstObject');
    });
  },

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

ofcourse.. wel that would make the redirect abit silly, so if you just want to wait for the list to load you could try:

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

  redirect: function() {
    var self = this;
    this.modelFor('doctors').then(function (list) {
           return list.get('firstObject');
       }).then(function (doctor){
           if(!doctor)
              self.transitionTo('doctor', doctor);
       });
  }
});
like image 148
Bram Avatar answered Dec 27 '22 01:12

Bram