EmberJS – Specifying a Route’s Model

You can specify a route’s model, by defining the template name in the route which is the same name as the data template, and implement its model hook.

Ember.Route.extend ({
   model: function() {
      return { //value-1 },{ //value-2 },{..},{ //value-n };
   }
});

In the above code value-1 to value-n variables are used to store the values which are being called in the template.

The following table lists down the different types of Specifying Routes model −

S.No.Specifying Routes & Description
1Dynamic Models
It defines the routes with dynamic segment which is used by Ember to access the value from URL.
2Multiple Models
You can define multiple models using the RSVP.hash which further uses the objects to return the promises.

Example

The following example shows how to specify a route for displaying data. Create a new route as specified in the previous chapters. Now open the router.js file with the following code to define the URL mappings −

import Ember from 'ember';                   
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config 

//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});

Router.map(function() {
   this.route('specifyroute');
});

//It specifies Router variable available to other parts of the app

export default Router;   

Create the application.hbs file and add the following code −

//link-to is a handlebar helper used for creating links
{{#link-to 'specifyroute'}}Click here to see details{{/link-to}}
{{outlet}} //It is a general helper, where content from other pages will 
appear inside this section

Open the specifyroute.hbs file created under app/templates/ with the following code −

<h2>List of Players</h2>
<ul>
   //The <i>each</i> helper to loop over each item in the array provided from model() hook
   {{#each model as |player|}}
      <li>{{player}}</li>
   {{/each}}
</ul>
{{outlet}}

To construct the URL, you need to implement model to return the values −

import Ember from 'ember';

export default Ember.Route.extend ({
   //The model() method returns the data which you want to make available to the template
   model() {
      return ['MS Dhoni', 'Steve Smith', 'Jason Roy','AB de Villiers','Kane Williamson'];
   }
});

Output

Run the ember server and you will receive the following output −

 route's model

When you click on the link in the output, it will generate a result as in the following screenshot −

 route's model

Previous Page:-Click Here

Leave a Reply