简体   繁体   中英

Backbone.js router passing parameter that is not in URL

I'm looking to call the same function with multiple routes in Backbone passing different parameter. However I don't want the passed parameter to be part of the URL.

app.routes = Backboone.Router.extend({
    routes: {
        "first": "display(0)"
        "second": "display(1)"
    },

    display: function(index){
        // do action with index
    }
})

So by visiting http://myapp.com/first , display get called and get passed the parameter of 0.

The current markup doesn't work and I like to ask if there is some way to do this because as far as I can find the only way to pass parameter to the "display" function is only via URL.

Thanks in advance.

There isn't a nice way to achieve that, you may be able to modify the args inside execute (which gets called before each route) but it seems like a hacky approach to something you could solve by just separating out into methods:

app.routes = Backboone.Router.extend({
    routes: {
        "first": "displayFirst"
        "second": "displaySecond"
    },

    displayFirst: function() {
        this.display(0);
    },

    displaySecond: function() {
        this.display(1);
    },

    display: function(index){
        // do action with index
    }
})

If you really want to try and do it in one method, you could try messing with stuff in execute :

execute: function(callback, args) {
    // mess with stuff before calling the callback, but why?
    callback.apply(this, args);
}

Dominic Tobias idea will work but it will get hard if you have a lot of different parameters to pass this is not a generic solution.

I don't know if this is the best way to do but you could use EventEmitter, https://github.com/Olical/EventEmitter

then the url is triggered by the route but the display function and the parameters are triggered by eventemitter at the same time.

It seems more generic in my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM