Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple routers vs single router in BackboneJs

All examples on Backbone I've seen use one router for the whole application, but wouldn't it make sense to have a router for each single part of your app (header, footer, stage, sidebar)? Has anyone built apps with more than one router and what are your experiences?

Let's think about a complex app with nested views: Wouldn't it be better when a view has its own router that handles the display of the subviews, than having one big router that has to inform the main view to change its subviews?

The background of this question: I've see a lot of parallels of the router in backbone and the ActivityMapper in GWT. The ActivityMapper is only responsible to get the right presenter for a given route and a given container in the DOM.

like image 253
Andreas Köberle Avatar asked Dec 02 '11 20:12

Andreas Köberle


1 Answers

i wrote an app (still writing) with multiple routers in it. however it is not like you think, it is more module based and not a router per view or anything like that.

for example, say i got two big modules in my app, 1 handling all books, and 1 for the users. books have multiple views (as do users), a list view, detail view, edit view, etc etc... so each module has its own router, which stands for its own set of urls:

// user module... var userRouter = Backbone.Router.extend({     routes: {         "users": "loadUsers",         "users/add": "addUser",         "user/:id": "loadUser",         "user/:id/edit": "editUser"     }  // ... rest dropped to save the trees (you never know if someone prints this out) });   // book module var bookRouter = Backbone.Router.extend({     routes: {         "books": "loadBooks",         "books/add": "addBook",         "book/:name": "loadBook",         "book/:name/edit": "editBook"     }  // ... rest dropped to save the trees (you never know if someone prints this out) }); 

so, it is not like my two routers are competing for the same route, they each handle their own set of routes.

edit now that I had more info via Elf Sternberg, I know it isn't possible by default to have multiple routers match on the same route. without a workaround like overriding the backbone history or using namespaces in routes and regexes to match these routes. more info here: multiple matching routes thanks Elf Sternberg for the link.

like image 55
Sander Avatar answered Sep 27 '22 19:09

Sander