Define a base url in Backbone.js router

2019-02-11 17:57发布

问题:

I want to be able to specify a base url for all my routes for development. Some of the devs have machines setup to work out of subdirectories instead of the application sitting at the webroot. I would like to only define these routes once. Instead of: routes: { "toms-subdirectory/users": "init_users" } I would like:

routes: {
    "/users": "init_users"
}

and be able to specify a baseurl for that installation so I could easily make it work across installs.

Right now I'm forcing them by defining a route object using bracket syntax to keep the dynamic keys and assigning that to the routes property inside the route. I was wondering if there is a cleaner way.

my_routes = {};
my_routes[window.webroot + '/users'] = 'init_users';

MyRoute = Backbone.Router.extend({ routes: my_routes })

回答1:

You can use Backbone.history.start like this

Backbone.history.start({
    pushState: true,
    root: "/public/search/"
});