I am trying to create backbone routes for a user dynamically , only if the logged in user has the permission to view that particular route.In my current implementation i have created the routes and call the corresponding routing function and in that function i will check , if the user has the required privilege, if not rerouted to a default page. Can i create the routes itself based on the condition so that i don't have to check every time whether user has the appropriate privileges.
var Workspace = Backbone.Router.extend({
routes: {
"help": "help",
"search/:query": "search",
"search/:query/p:page": "search",
"default": "default"
},
help: function() {
if(!permission1){
router.navigate('default', true);
}
//write logic
},
search: function(query, page) {
if(!permission2){
router.navigate('default', true);
}
//write logic
},
//write logic for other routes
});
The solution to the problem i came up with after reading the backbone js documentation is as follows:
var GlobalRouter = Backbone.Router.extend({
initialize: function () {
this.route('*path','default',showDefault);
if (permission1) {
this.route('menu1', 'menu1', showMenu1);
}
if (permission2) {
this.route('menu2', 'menu2', renderMenu2);
}
if (permission3) {
this.route('menu3', 'menu3', renderMenu3);
}
}
});
Creating the routes likes this means that if a user does not have permission to view a certain route , there is no need for checking permission again as the routing will not happen as it is never created.