Managing parameters of a pair of a pair of values ​​in Backbone.js Router

I want to pass pairs of key values ​​as parameters for trunk routes and I want them to deserialize to a javascript object before calling the displayed function.

var MyRouter = Backbone.Router.extend({ routes: { "dashboard?:params" : "show_dashboard" }, show_dashboard: function(params){ console.log(params); } }); 

When I switch to "http: //...#dashboard? Key1 = val1 & key2 = val2", then {console1: "val1", key2: "val2"} should be printed to the console.

Currently, the jQuery BBQ $ .deparam method is used inside each function displayed to access a deserialized object. It would be nice if I could extend the Router and define it only once, so that the parameters are available in all displayed functions as an object. What would be a clean way to do this? And are there any pitfalls in this?

Many thanks,

mano

+8
javascript params query-parameters
source share
1 answer

You must override the _extractParameters function in Backbone.Router . Then all functions of the router will be called with the first parameter being the params object.

 // Backbone Router with a custom parameter extractor var Router = Backbone.Router.extend({ routes: { 'dashboard/:country/:city/?:params': 'whereAmIActually', 'dashboard/?:params': 'whereAmI' }, whereAmIActually: function(params, country, city){ console.log('whereAmIActually'); console.log(arguments); }, whereAmI: function(params){ console.log('whereAmI'); console.log(arguments); }, _extractParameters: function(route, fragment) { var result = route.exec(fragment).slice(1); result.unshift(deparam(result[result.length-1])); return result.slice(0,-1); } }); // simplified $.deparam analog var deparam = function(paramString){ var result = {}; if( ! paramString){ return result; } $.each(paramString.split('&'), function(index, value){ if(value){ var param = value.split('='); result[param[0]] = param[1]; } }); return result; }; var router = new Router; Backbone.history.start(); // this call assumes that the url has been changed Backbone.history.loadUrl('dashboard/?planet=earth&system=solar'); Backbone.history.loadUrl('dashboard/usa/la/?planet=earth&system=solar'); 

Working demo here .

+10
source share

All Articles