Skip to content

Instantly share code, notes, and snippets.

@Craga89
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save Craga89/a3f11a458c8b662e9046 to your computer and use it in GitHub Desktop.

Select an option

Save Craga89/a3f11a458c8b662e9046 to your computer and use it in GitHub Desktop.
Durandal - Type cast queryString parameters. See http://blog.craigsworks.com/durandal-type-cast-querystring-parameters/
/**
AMD module, **to be included before the rest of your durandal app**, that enhances
the native `router.parseQueryString` method, providing query parameters in their
correct primitive type, rather than always as strings.
@module Durandal.Router.Addons
**/
define('plugins/router', function(router) {
/**
Parses a query string into an object, attempting to parse each query string param
into a proper type
@method parseQueryString
@for Durandal.Router
@param {String} queryString The query string to parse.
@return {Object} An object keyed according to the query string parameters.
**/
var _parseQueryString = router.parseQueryString;
router.parseQueryString = function () {
var queryObject = _parseQueryString.apply(this, _.rest(arguments)),
val, key;
for(key in queryObject) {
val = queryObject[key];
// Float
if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) {
val = parseFloat(val);
}
// Integer
else if (/^[+-]?[0-9]+$/.test(val)) {// simple int regex
val = parseInt(val, 10);
}
// Booleans
val = (!val && val !== 0) ? true : val;
(val === 'true') && (val = true);
(val === 'false') && (val = false);
// Couldn't convert it, use the original value!
if (val !== false && val !== true && !_.isNumber(val)) {
val = val;
}
// Set the new value
queryObject[key] = val;
}
return queryObject;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment