EmberJS-Router After the Model is Known



Description

Use the afterModel or redirect hook to get information about the current model which decides about the redirection. They receive two parameters i.e. resolve model and the transition.

Syntax

Ember.Route.extend({
  afterModel: function(posts, transition) {
      this.transitionTo('routeName', posts.get('firstObject'));
   }
});

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs After the Model is Known</title>
      <!-- CDN's -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script>
      <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script>
      <script src="https://builds.emberjs.com/release/ember.debug.js"></script>
      <script src="https://builds.emberjs.com/beta/ember-data.js"></script>
   </head>
   <body>
      <script type="text/x-handlebars" data-template-name="application">
         {{outlet}}
      </script>

      <script type="text/x-handlebars" data-template-name="index">
         <a href="#" {{action "getIds"}}>Click To Get IDs Of Student</a>
      </script>

      <script type="text/x-handlebars" data-template-name="posts">
         <b>Student Id:</b> <i>{{stud_id}} </i><br/>
      </script>

      <script type="text/javascript">
         App = Ember.Application.create({});

         App.Router.map(function() {
            this.route('posts', { path: 'school/:stud_id'});
         });

         App.IndexController = Ember.Controller.extend({
            actions: {
               getIds: function() {
                  this.transitionToRoute('posts', { stud_id: 1 });
               }
            }
         });

         App.IndexRoute = Ember.Route.extend({
            afterModel: function(params) {
               return params;
            }
         });
      </script>
   </body>
</html>

Output

Let's carry out the following steps to see how above code works:

  • Save above code in routing_aftr_mod.htm file

  • Open this HTML file in a browser.

Advertisements