To get that I extended Backbone.Router. I wish my router helps you. I added a property toEvaluate with the preconditions by route and I added evaluateRoutesFn with the function that will evaluate them before to navigate some route.
An example of my route could be:
var MySubRouter = Backbone.ModuleRoute.extend({
//hasPermissions is static
//if you want a function of an instance you can use a function instead
evaluateRoutesFn: SomeView.hasPermissions,
toEvaluate: {
routeA: {
modulePreconditions: [SomeView.CONDITION_A, ...]
}
},
routeA: function(param1, param2) {
//the route to navigate with preconditions
},
The method with the permissions return true or false or an error.
var MyView = ModuleView.extend({}, {
CONDITION_A: "conditionA",
hasPermissions: function (condition, properties) {
switch (condition) {
case MyView.CONDITION_A:
return app.ConditionA;
default:
return true;
}
}
});
And the more important is ModuleRoute. Here you have the base of my moduleRoute. I added more things. Like error control. I saved all the current routes in each module of my app... And more. You can add whatever you need. It is really useful.
Backbone.ModuleRoute = Backbone.Router.extend({
evaluateRoutesFn: null,
toEvaluate: null,
constructor: function (prefix, options) {
this._finalRoutes = {};
Backbone.SubRoute.prototype.constructor.call(this, prefix, options);
},
onRoutes: function (route) {
var aps = Array.prototype.slice;
var args = aps.call(arguments);
args.shift();
var routeName = this.routes[route];
var evalResult = true;
try {
var toEval = this.toEvaluate && this.toEvaluate[routeName];
if (toEval) {
evalResult = this.evalPreconditions(toEval.modulePreconditions, args);
//more future preconditions
}
}
catch (err) {
evalResult = false;
}
if (evalResult)
try {
this._finalRoutes[route].apply(this, args);
}
catch (err) {
window.history.back(); //go back, error control...
}
else
window.history.back(); //no permissions, go back
},
evalPreconditions: function (preconds, args) {
if (!this.evaluateRoutesFn) {
throw "WARNING: Evaluate routes function must be overriden to evaluate them. " +
"Don't assign toEvaluate if you won't do it. The evaluation has been skipped.";
}
if (!preconds)
return true;
var evalResult = true;
for (var i = 0, len = preconds.length; i < len; i++) {
evalResult = this.evaluateRoutesFn(preconds[i], args);
if (!evalResult) {
throw "ERROR: The precondition is not truth.";
break;
}
}
return evalResult;
},
route: function (route, name, callback) {
this._finalRoutes[route] = (!callback) ? this[name] : callback;
var that = this;
callback = function (path) {
return function () {
var aps = Array.prototype.slice;
var args = aps.call(arguments);
args.unshift(path);
that.onRoutes.apply(that, args);
};
} (route);
return Backbone.Router.prototype.route.call(this, route, name, callback);
}
});