문제

I'm looking for something to accomplish in Backbone. Here is the explanation.

I have backbone routes like

{
    '': 'defaultRoute',
    'test': 'test',
    'testing': 'testing'
}

Assuming my root url is '/routes'

Now when I say 'router.navigate('test', {trigger: true});' url changes to /routes/test.

Similar way when I call 'router.navigate('testing', {trigger: true});' url changes to /routes/testing.

But when I call 'router.navigate('', {trigger: true});' url changes to /routes/.

You know i didn't expect that / at the end. I never passed that. It should have been back to root url i.e. '/routes'.

Adding / at the end makes lot of difference/meaning. Checkout 'http://googlewebmastercentral.blogspot.in/2010/04/to-slash-or-not-to-slash.html'

Any fix for that (i.e. not having / at the end for default route)?

도움이 되었습니까?

해결책 3

Update:-

This has been already fixed in Backbone's latest version. I asked a question on there forum and found the answer. I'm adding it here as an answer if it helps anyone who is looking for the same thing.

https://github.com/jashkenas/backbone/issues/2871

다른 팁

Try to override Backbone.History.prototype.navigate.

Copy default function and change this line :

  var url = this.root + fragment;

to :

  if(this.root !== '/' && fragment === ''){
    var url = this.root.replace(trailingSlash, '');
  }else{
    var url = this.root + fragment;
  }

First things first:

If your application is not being served from the root url / of your domain, be sure to tell History where the root really is, as an option: Backbone.history.start({pushState: true, root: "/public/search/"}) Backbone#History

In your case, it is most likely to be something like root: "/routes". Something you need to keep in mind is that your website is seen in the browser as either a resource or a remote folder, therefore the default route without a trailing slash may not fully work by just leaving it as "" because that means usually "the current folder". You could try to set your root url as root: "/" instead (just as it should be by default) and create a "routes" resource as your default route, something like the following:

{
    'test':    'test',
    'testing': 'testing',
    'routes':  'defaultRoute',
    '*':       'catchAll'
}

Another recommendation that I am doing to you (as you can see it above) is to set your a catch all URL at the end in case someone enters a non-existent one, and you can also use it to redirect your users to your default route.

// your code above ...
defaultRoute: function() {
  // your default route code...
},

catchAll: function() {
  this.navigate('routes', {trigger: true});
}
// your code below ...

Finally, by any reason mess up with Backbone URLs manually, you are highly risking yourself to break the whole thing AND if in the future the API changes it should be easier to update if you just follow the intended use.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top