Multiple routers

In general, you only need a single Router to power your entire site. However, if you have reason to do so, you can easily include multiple Routers, and Backbone will happily allow this. If two or more Routers on the same page match a particular route, Backbone will trigger the route from the first Router with a matching route defined.

There are two main reasons why you should use multiple Routers. The first reason is to separate your routing into logical groups. For instance, in an earlier example, we used a conditional to add certain admin-only routes to the Router class when the current user was an administrator. If our site has enough of these routes, it might make sense to create a separate Router for the admin-only routes, as follows:

var NormalRouter = Backbone.Router({
     routes: {
        // routes for all users would go here
    }
};
var AdminRouter = Backbone.Router({
     routes: {
        // routes for admin users only would go here
    }
};
new NormalRouter();
if (user.get('isAdmin') {
    new AdminRouter();
}

The other reason why you need to use multiple Routers is when you have two different sites that need to share some common code. For instance, a book-selling site might want a main site for their shoppers to buy books and an entirely different site for publishers to submit new books. However, even though the sites are different, they might both want to share some common code, such as a Book Model or a book-rendering View. By using multiple Routers, our bookseller can share any code they want between the two sites, while keeping the pages/routes of each entirely separate from one another.

In practice though, using multiple Routers can be confusing, especially if they have overlapping routes. Since you can easily add routes dynamically (as we did with our earlier administrator example), there typically won't be any need for you to rely on multiple Routers and you will likely avoid confusion by sticking to only one.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.151.153