Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emberjs using "needs" but other controller model empty

Tags:

ember.js

How do I get the the model to load without going to the route first?

App.UsersRoute = Em.Route.extend({
  model: function() {
      return ['bob', 'sue', 'tom'];
  },

  setupController: function(controller, model) {
    controller.set('model', model);
  }
});

From another controller using

needs: "users"

and

this.get('controllers.users.content');

works fine as long as I visit the UsersRoute first.

like image 909
gp. Avatar asked Nov 21 '13 03:11

gp.


2 Answers

Load it in the topmost route that will need it, thusly:

App.SomeOtherRoute = Em.Route.extend({
  setupController: function(controller, model) {
    controller.set('model', model);
    this.controllerFor('user').set('model', ['bob', 'sue', 'tom']);
  }
});

Note that if you are using ember-data or epf or ajax, that the model will be a promise. You can't set the model on a controller to be a promise so you would do:

  setupController: function(controller, model) {
    controller.set('model', model);
    return this.get('store').findAll('user').then(function(users) {
      this.controllerFor('users').set('model', users);
    });
  }

Note in the second one I'm using UsersController, not UserController, because you seem to want a collection of users not a single user.

like image 109
Michael Johnston Avatar answered Oct 03 '22 13:10

Michael Johnston


I hit this same problem this past weekend and the following worked for me:

App.SomeOtherController = Ember.Controller.extend({
  needs: ['users']
});

App.SomeOtherRoute = Ember.Route.extend({
    setupController: function( controller, model ){
      this._super( controller, model );
      controller.set( 'controllers.users.model', ['bob', 'sue', 'tom'] );
    }
});

if it is an ajax call / ember data then you need something like this:

App.SomeOtherController = Ember.Controller.extend({
  needs: ['users']
});

App.SomeOtherRoute = Ember.Route.extend({
    setupController: function( controller, model ){
      this._super( controller, model );
      this.get('store').findAll('user').then(function(users) {
        controller.set( 'controllers.users.model', users );
      });
    }
});

However, a colleague pointed out to me during our code review today that if I need to do this I have probably structured my routes / resources / models incorrectly. In other words an outer route should not depend on an inner route's model. So I am now thinking about going back and refactoring this so that the users model is part of the model for the outer route and then I can use that in my inner route controller.

like image 28
Alec Rooney Avatar answered Oct 03 '22 13:10

Alec Rooney