How can I set all route have the same method or action when I use ember?

187 views Asked by At

My ember application use 1.11.3 version and ember-simple-auth(0.7.3). All of route must set the AuthenticatedRouteMixin and get the account infomation use beforeModel, I think is not good way to do this. Example:

App.Route = Ember.Route.extend(AuthenticatedRouteMixin, {
  beforeModel: function() {
    Account.find().then(function(user) {
      this.set('user', user);
    })
  },
  setupController: function(controller, model) {
    controller.set('model', model);
    controller.set('user', this.get('user'));
  }
});

App.ApplicationRoute = App.Route.extend();

I set a jsbin: http://emberjs.jsbin.com/wipasusige/1/edit?html,js,console,output

If my all route use App.Route.extend();, it is has problem is AuthenticatedRouteMixin can not work.

I use Route.extent set all to route beforeModel to get the account infomations is a good way?

Maybe there is any better way to approach this problem?

1

There are 1 answers

1
Andrey Mikhaylov - lolmaus On

As this customization makes sense only with the AuthenticatedRouteMixin, it makes sense to perform it in the mixin itself!

App.CustomAuthenticatedRouteMixin = AuthenticatedRouteMixin.extend({

  beforeModel: function() {
    // We do not want the default functionality to be removed
    var superResult = this._super(transition);

    var accountPromise =
      Account
        .find()
        .then(function(user) {
          this.set('user', user);
          return superResult;
        }.bind(this));

    return accountPromise;
  },

  setupController: function(controller, model) {
    controller.set('model', model);
    controller.set('user', this.get('user'));
    this._super(controller, model);
  }

});

Then reuse it in routes as you would normally do with the AuthenticatedRoutMixin.

Mixins allow composing classes from various functionality sources which is a more flexible approach than inheriting from a single source class.

Disclaimer: the above code is just a concept, not a fully working solution. You'll have to think how to implement it in your project.