Adding a Show Route
Learn how to separate the URLs of our contacts from the root URL based on their contact IDs using routing in Marionette.
Let’s add a route to show a given contact. In other words, we’ll add a route handler for URL fragments that look like contacts/3
, where 3
would be the contact’s id
.
Declaring routes for contacts
For declaring routes for contacts, we need to add their routing paths as a URL fragment, which will identify them uniquely based on their IDs.
Route using URL fragment
Let’s start by taking care of displaying the contact when a URL of this type is clicked, by adding it to our ContactsApp
file:
ContactManager.module("ContactsApp", function(ContactsApp,ContactManager, Backbone, Marionette, $, _){ContactsApp.Router = Marionette.AppRouter.extend({appRoutes: {"contacts": "listContacts","contacts/:id": "showContact"}});var API={listContacts: function(){ContactsApp.List.Controller.listContacts();},showContact: function(id){ContactsApp.Show.Controller.showContact(id);}};ContactManager.on("contacts:list", function(){ContactManager.navigate("contacts");API.listContacts();});ContactsApp.on("start", function(){new ContactsApp.Router({controller: API});});});
In line 6, we declare the route. Notice that we can provide parameters such as :id
to match a single URL component between slashes and providing it to the controller’s handling function.
Now, we extract the contact’s id
from the URL. We send it on to our trusty Show
controller in line 16 to display the data, except that we’re providing an id
integer when the controller’s expecting a model ...