Skip to content Skip to sidebar Skip to footer

Key Value Pair Params Handling In Backbone.js Router

I want to pass key value pairs as params to Backbone routes and want it to be deserialized to a javascript object before the mapped function is called. var MyRouter = Backbone.Rou

Solution 1:

You should redefine _extractParameters function in Backbone.Router. Then all router functions will be invoked with the first parameter being params object.

// Backbone Router with a custom parameter extractorvarRouter = 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 analogvar 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 = newRouter;
Backbone.history.start();

// this call assumes that the url has been changedBackbone.history.loadUrl('dashboard/?planet=earth&system=solar');
Backbone.history.loadUrl('dashboard/usa/la/?planet=earth&system=solar');

The working demo is here.

Post a Comment for "Key Value Pair Params Handling In Backbone.js Router"