The main idea - pass {router: routerInstance} as controller option.
This allows to define controller specific routes in separated controllers.
When url changes from #dogs / #dogs/:id to any route which defined in another controller, remove method is calling automatically.
This case controller should clear state, remove controller specific views and models.
Controller can automatically add router without creating Backbone.Router instance
var CatsController =Backbone.Controller.extend({
routes:{
'cats':'list',
'cats/:id':'showCat'
},
initialize:function(){
// do some init stuff
},
list:function(){
// show cats list
},
showCat:function(catId){
// show cat view
}
});
var DogsController =Backbone.Controller.extend({
routes:{
'':'list',
'dogs':'list',
'dogs/:id':'showDog'
},
initialize:function(){
// do some init stuff
},
list:function(){
// show dogs list
},
showDog:function(catId){
// show cat view
}
});
var cats =newCatsController({router:true});
var dogs =newDogsController({router:true});
Before / after routing
Controller automatically calls onBeforeRoute / onAfterRoute functions when processing routes.
var DogsController =Backbone.Controller.extend({
routes:{
'':'list',
'dogs':'list'
},
initialize:function(){
// do some init stuff
},
onBeforeRoute:function(url,param1,param2,...){
// called before `#dogs` / `#` routes
// Set some state variables, create controller layout etc
},
onAfterRoute:function(url,param1,param2,...){
// called after `#dogs` / `#` routes
},
list:function(){
// show dogs list
}
});
var dogs =newDogsController({router:true});
//Cancel route
var DogsController =Backbone.Controller.extend({
routes:{
'dogs':'list',
'dogs/:id':'showDog'
},
initialize:function(){
// do some init stuff
},
list:function(){
// show dogs list
},
showDog:function(catId){
// show cat view
},
onBeforeRoute:function(url){
console.log('before route');
var deferred =Q.defer();
setTimeout(function(){
deferred.resolve('ggg');
},2000);
returndeferred.promise;
//return false;
},
onAfterRoute:function(){
console.log('afterRoute');
}
});
var dogs =newDogsController({router :true});
Backbone.history.start();
Redirecting to another route
If declarative routing has been used in project, you don't have access directly to Router instance.
Backbone Controller provides Controller.navigate method as proxy for Backbone.Router.navigate method.