Skip to content Skip to sidebar Skip to footer

Backbone.js Slash After Hash In Fallback - History Pushstate

I'm using Backbone.js's routing. It generate urls for browsers like this: http://my-app.com/help For Internet Explorers (except IE10) and old non-HTML5 browsers: http://my-app.com

Solution 1:

I know this is a bit old, but since the accepted answer no longer works in newer versions of Backbone, I figured I would share my findings.

I found a way to get this to work in IE8 and Chrome (have not testing any other browsers) - if you are using Backbone.history for navigation.

If you use two preceding slashes in the navigate call, it will create the Url like you want it.

Backbone.history.navigate('//help');

I did not change the routes at all - they do not start with a slash. Putting a slash there seemed to break it.

I should also note that I am using Marionette with Backbone as perhaps that could make a difference.

I hope this helps someone.

Solution 2:

I do believe that your 2nd code block is entirely different than the 3rd. The preceding slash is set on the property name.

routes: {
    "help":                 "help",    //#help"search/:query":        "search",  //#search/kiwis"search/:query/p:page": "search"   // #search/kiwis/p7
  }

is different than:

routes: {
    "/help":                 "help",    //#/help"/search/:query":        "search",  //#/search/kiwis"/search/:query/p:page": "search"   // #/search/kiwis/p7
  }

Solution 3:

Here's an ugly hack to get around it: override getHash(). Here's the original code:

getHash: function(windowOverride) {
  var loc = windowOverride ? windowOverride.location : window.location;
  var match = loc.href.match(/#(.*)$/);
  return match ? match[1] : '';
},

It seems to work after adding an extra slash to the regexp:

Backbone.History.prototype.getHash = function(windowOverride) {
  var loc = windowOverride ? windowOverride.location : window.location;
  var match = loc.href.match(/#\/(.*)$/);
  return match ? match[1] : '';
}

Navigate might not work after this, but it could probably be fixed with a similar hack.

Post a Comment for "Backbone.js Slash After Hash In Fallback - History Pushstate"