Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - 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.Router.extend({
  routes: {
    "dashboard?:params" : "show_dashboard"
  },
  show_dashboard: function(params){
     console.log(params); 
  }
}); 

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

Am currently using jQuery BBQ's $.deparam method inside each mapped function to get at the deserialized object. It would be nice if I can extend Router and define it just once so params is accessible inside all mapped functions as an object. What would be a clean way to do this? And are there some pitfalls in this??

Much thanks,

mano

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 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');

The working demo is here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...