Route#beforeModel()

beforeModel (transition) Promisepublic

Defined in packages/ember-routing/lib/system/route.js:1257

This hook is the first of the route entry validation hooks called when an attempt is made to transition into a route or one of its children. It is called before model and afterModel, and is appropriate for cases when:

1) A decision can be made to redirect elsewhere without needing to resolve the model first. 2) Any async operations need to occur first before the model is attempted to be resolved.

This hook is provided the current transition attempt as a parameter, which can be used to .abort() the transition, save it for a later .retry(), or retrieve values set on it from a previous hook. You can also just call this.transitionTo to another route to implicitly abort the transition.

You can return a promise from this hook to pause the transition until the promise resolves (or rejects). This could be useful, for instance, for retrieving async code from the server that is required to enter a route.

App.PostRoute = Ember.Route.extend({
  beforeModel: function(transition) {
    if (!App.Post) {
      return Ember.$.getScript('/models/post.js');
    }
  }
});

If App.Post doesn't exist in the above example, beforeModel will use jQuery's getScript, which returns a promise that resolves after the server has successfully retrieved and executed the code from the server. Note that if an error were to occur, it would be passed to the error hook on Ember.Route, but it's also possible to handle errors specific to beforeModel right from within the hook (to distinguish from the shared error handling behavior of the error hook):

App.PostRoute = Ember.Route.extend({
  beforeModel: function(transition) {
    if (!App.Post) {
      let self = this;
      return Ember.$.getScript('post.js').then(null, function(e) {
        self.transitionTo('help');

        // Note that the above transitionTo will implicitly
        // halt the transition. If you were to return
        // nothing from this promise reject handler,
        // according to promise semantics, that would
        // convert the reject into a resolve and the
        // transition would continue. To propagate the
        // error so that it'd be handled by the `error`
        // hook, you would have to
        return Ember.RSVP.reject(e);
      });
    }
  }
});

Parameters:

transition Transition

Returns:

Promise
if the value returned from this hook is a promise, the transition will pause until the transition resolves. Otherwise, non-promise return values are not utilized in any way.
doc_EmberJs
2016-11-30 16:53:04
Comments
Leave a Comment

Please login to continue.