更新
http://www.geekdave.com/2012/04/05/module-specific-subroutes-in-backbone/
var MyApp = {};
MyApp.Router = Backbone.Router.extend({
routes: {
// general routes for cross-app functionality
"" : "showGeneralHomepage",
"cart" : "showShoppingCart",
"account" : "showMyAccount",
// module-specific subroutes:
// invoke the proper module and delegate to the module's
// own SubRoute for handling the rest of the URL
"books/*subroute" : "invokeBooksModule",
"movies/*subroute" : "invokeMoviesModule",
"games/*subroute" : "invokeGamesModule",
"music/*subroute" : "invokeMusicModule"
},
invokeBooksModule: function(subroute) {
if (!MyApp.Routers.Books) {
MyApp.Routers.Books = new MyApp.Books.Router("books/");
}
},
invokeMoviesModule: function(subroute) {
if (!MyApp.Routers.Movies) {
MyApp.Routers.Movies = new MyApp.Movies.Router("movies/");
}
},
invokeGamesModule: function(subroute) {
if (!MyApp.Routers.Games) {
MyApp.Routers.Games = new MyApp.Games.Router("games/");
}
}
});
// Actually initialize
new MyApp.Router();
});
MyApp.Books.Router = Backbone.SubRoute.extend({
routes: {
/* matches http://yourserver.org/books */
"" : "showBookstoreHomepage",
/* matches http://yourserver.org/books/search */
"search" : "searchBooks",
/* matches http://yourserver.org/books/view/:bookId */
"view/:bookId" : "viewBookDetail",
},
showBookstoreHomepage: function() {
// ...module-specific code
},
searchBooks: function() {
// ...module-specific code
},
viewBookDetail: function() {
// ...module-specific code
},
});
[旧]
有多种方法可以做到这一点,我更喜欢的方式是:
var Router = Backbone.Router.extend({
initialize : function(){
app.homeView = new HomeView({el:"body"}); //I prefer calling it ShellView
},
routes : {
"subView/*":"renderS",
},
renderSubViewOne : function(params){
app.homeView.renderSubView('one',params);
}
});
var HomeView = Backbone.View.extend({
renderSubView:function(viewName, params){
switch(viewName){
case 'one':
var subViewOne = new SubViewOne({el:"tab-one"},params); //_.extend will be cleaner
break;
}
}
});
上面的代码只是给出一个想法的框架。如果应用比较复杂,我建议使用多个路由器。
Multiple routers vs single router in BackboneJs