Skip to content

Instantly share code, notes, and snippets.

@nanotronic
Created March 19, 2013 16:11
Show Gist options
  • Save nanotronic/5197453 to your computer and use it in GitHub Desktop.
Save nanotronic/5197453 to your computer and use it in GitHub Desktop.
Allowing optional parameters for can.Control.route. E.g.: docs/:section(/:subsection) > create two routes: docs/:section and docs/:section/:subsection docs(/:section)(/:subsection) > create three routes: docs, docs/:section and docs/:section/:subsection
define(['can/util/library', 'can/route', 'can/control'], function (can) {
var optionalParam = /\((.*?)\)/g,
escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
var getOptionalParam = function(route){
return route.replace(escapeRegExp, '\\$&').match(optionalParam);
};
// ## control/route.js
// _Controller route integration._
can.Control.processors.route = function (el, event, selector, funcName, controller) {
selector = selector || "";
if(!getOptionalParam(selector)){
can.route(selector);
var batchNum, check = function (ev, attr, how) {
if (can.route.attr('route') === (selector) && (ev.batchNum === undefined || ev.batchNum !== batchNum)) {
batchNum = ev.batchNum;
var d = can.route.attr();
delete d.route;
if (can.isFunction(controller[funcName])) {
controller[funcName](d);
} else {
controller[controller[funcName]](d);
}
}
};
can.route.bind('change', check);
return function () {
can.route.unbind('change', check);
};
}else{
var optionals = getOptionalParam(selector),
ret = [];
do {
var sel = selector.replace(optionals.toString().replace(',', ''), '').replace(/[\(\)]/g, '');
ret.push(can.Control.processors.route(el, event, sel, funcName, controller));
}while (optionals.shift());
return function(){
can.each(ret || [], function(value){
value();
});
};
}
};
return can;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment