bodokaiser
bodokaiser

Reputation: 15742

Backbone.Router accept query and path

I want that my Backbone.Router instance listens on hashbangs like '#/settings' and '#/settings/privacy'

Currently I handle this problem this way:

var Router = Backbone.Router.extend({

    routes: {
         "settings": "settings",
         "settings/:query": "settings"
    },

    settings: function(query) {
        // do the routing
    }

});

I would now like to do this whole stuff in only one route. Unfortunately 'settings/:query' would only allow 'settings/'

Any one an idea how to handle this?

Regards

Upvotes: 0

Views: 317

Answers (1)

mu is too short
mu is too short

Reputation: 434615

You have some options here. If you're happy with routes like #settings/ (note the final slash) and #settings/privacy, then you can use this:

routes: {
    'settings/*query': 'settings'
}

Demo: http://jsfiddle.net/ambiguous/m7ufD/

That won't work with just #settings though, the final slash is necessary for that route to work.

If you don't have any routes like #settings-something-else, then you could do this:

routes: {
    'settings*query': 'settings'
}

Demo: http://jsfiddle.net/ambiguous/MudaG/

That would also match things like #settingsandstuff and it would leave the slash in the route handler's argument (i.e. the function would get '/privacy' instead of just 'privacy').

The most flexible option is to use route directly with a regex, then you can match #settings and #settings/privacy with a single route without either of the above problems:

// No routes, do it in initialize instead
initialize: function() {
    this.route(/^settings(?:\/(.*)|)$/, 'settings');
}

Demo: http://jsfiddle.net/ambiguous/XGrQz/

That won't match #settings-and-stuff and it won't include the leading slash in the function's argument for #settings/privacy.

Upvotes: 1

Related Questions