5

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.

Community
  • 1
  • 1
Robert Jackson
  • 534
  • 3
  • 7

1 Answers1

1

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);
       });
  }
});
Bram
  • 765
  • 1
  • 6
  • 14
  • I tried following this example, but the list I get have length 0 so the firstObject is undefined. Any work around? Thanks in advance! – wen Jun 12 '13 at 17:48
  • well i gues your list is empty then. i supose you could always redirect to another route.. I'll put in below there. (just an idear.. let me know if it does not work) – Bram Jun 13 '13 at 18:55
  • I'm pretty sure I get results from the server, but the "return list.get('firstObject') line is still triggered before the list is available. – wen Jun 17 '13 at 17:23