Created
March 19, 2013 16:11
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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