Book Image

Backbone.js Patterns and Best Practices

By : Swarnendu De
Book Image

Backbone.js Patterns and Best Practices

By: Swarnendu De

Overview of this book

Table of Contents (19 chapters)
Backbone.js Patterns and Best Practices
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Precompiling Templates on the Server Side
Index

Working with routers


The Backbone router provides methods to route client-side pages by using hash fragments or standard URLs as per the History API. Routes that use the hash fragments or History API may look like this:

// Hash fragment
http://www.foo.com/#user/23

// Standard URL
http://www.foo.com/user/23

The routes and actions that will be triggered when the URL fragment matches the specific routes are defined in the routes object of the router:

routes: {
  'users' : 'showUsers',
  'user/:id' : 'showUserDetails',
  'user/:id/update' : 'updateUser'
}

Now, let's see how we can create a basic router. Assume that we are developing an application with a few modules, among which the User module is an important one.

var AppRouter = Backbone.Router.extend({
  routes: {
    'users': 'showUsers',
    'user/:id': 'showUserDetails',
    'user/:id/update': 'updateUser',
    'user/:id/remove': 'removeUser'
  },

  showUsers: function () {
    // Get all the user details from server and 
    // show the...