Blog

A currentUser Helper for Ember Routes

In many of my Ember routes I need to be sure that I have a populated currentUser, so I can direct users and protect certain pages appropriately. In a completely asynchronous environment like Ember, it can be hard to know when an important call has resolved. Here's my stab at a little helper (for an Ember.Route) that will make sure currentUser is available when your route's .model() method runs.

// define it

App.CurrentUserHelper = {
  beforeModel: function() {
    if (!this.controllerFor('application').get('currentUser')) {
      var auth_deferred = $.get(App.Host + '/session');

      auth_deferred.then(function(user) {
        this.controllerFor('application').set('currentUser', user);
      }.bind(this));

      return auth_deferred;
    } 
  },
  currentUser: function() {
    return this.controllerFor('application').get('currentUser');
  }.property()
}

Then extend your route with it:

App.NewPostRoute = Ember.Route.extend(App.CurrentUserHelper, {
  model: function() {
    if (!this.get('currentUser')) {
      this.transitionTo('posts');
      return;
    }
    return this.store.createRecord('post');
  },
});

It takes advantage of the fact that Ember resolves any deferred returned from a route's beforeModel() method before calling .model(). Now, anytime you extend a route with App.CurrentUserHelper, you can be sure that this.get('currentUser') will be ready for you.