Skip to content

Step 6 - Add Router

Compare
Choose a tag to compare
@dmytroyarmak dmytroyarmak released this 03 Feb 09:15
  1. 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>
    
  2. 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();
    
  3. Redirect from home to contacts using router.navigate():

      router.on('route:home', function() {
        router.navigate('contacts', {
          trigger: true,
          replace: true
        });
      });
    
  4. 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);
    });
    

Difference