Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone router with multiple parameters

I need to get this to work:

routes: {
  ':product' : 'showProduct',
  ':product/:detail': 'showProductDetail'

showProductDetail never gets called while the ':product' route is set even if it is set afterwards. I tried the following

routes: {
  ':product(/:detail)': showProductOrDetail
}

But this will not get called when only the second parameter changes. It is important that I have the product itself or the product and detail in the url.

Does anyone know how to fix this?

like image 724
matteok Avatar asked Nov 14 '13 12:11

matteok


2 Answers

There's a little hacky solution to your problem. I have a feeling there is a nicer way to do this but that should work:

routes: {
    "product/:id": "showProduct",
    "product/:id/details/:did": "showDetails"
},

showProduct: function(id) {
    this.showDetails(id);
},

showDetails: function(id, did) {
    // Check did for undefined

}
like image 161
Szymon Drosdzol Avatar answered Oct 13 '22 01:10

Szymon Drosdzol


A late response (over a year).. but you can use RegEx in a backbone router to achieve this. My example presumes the parameters are going to start with a number.

ie: localhost:8888/#root/1param/2param

var router = Backbone.Router.extend({
    initialize: function () {
        // Use REGEX to get multiple parameters
        this.route(/root/, 'page0'); 
        this.route(/root\/(\d+\S+)/, 'page1'); 
        this.route(/root\/(\d+\S+)\/(\d+\S+)/, 'page2');
    },
    page0:function(){
        console.log("no id");
    },
    page1:function(id1){
        console.log(id1);
    },
    page2:function(id1,id2){
        console.log(id1);
        console.log(id2);
    }
});

Hope this helps.

like image 23
jstleger0 Avatar answered Oct 13 '22 01:10

jstleger0