Step 6 - Add Router
-
Create js/router.js file with our router:
ContactManager.Router = Backbone.Router.extend({ routes: { '': 'home', 'contacts': 'showContacts', 'contacts/new': 'newContact', 'contacts/edit/:id': 'editContact' } });
and in index.html:
<script src="app/js/router.js"></script>
-
Instantiate router in app start method and start backbone history:
var router = new ContactManager.Router(); router.on('route:home', function() { console.log('Home'); }); router.on('route:showContacts', function() { console.log('Show contacts'); }); router.on('route:newContact', function() { console.log('New contact'); }); router.on('route:editContact', function(id) { console.log('Edit contact'); }); Backbone.history.start();
-
Redirect from home to contacts using router.navigate():
router.on('route:home', function() { router.navigate('contacts', { trigger: true, replace: true }); });
-
Show contacts only on contacts path:
router.on('route:showContacts', function() { var contactsView = new ContactManager.Views.Contacts({ collection: contacts }); $('.main-container').html(contactsView.render().$el); });