Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Router in IE

I am using the Backbone.js router to fire certain initialization methods when the user hits certain URL routes. So going to /posts/1 via a vanilla anchor tag should fire whatever callback is associated with /posts/:id in my Backbone router. This works fine in modern browsers when Backbone.history.start({ pushState : true }) is set. However, in IE, users who try to hit /posts/1 will be redirected to /#posts/1, which is just my home page with a meaningless hash string.

To be clear, I do not need pushState. I am not trying to push URLs to the browser history. I am just trying to read them, then fire a callback, which should be feasible in any browser.

Seems like simple functionality but I am stumped.

Thanks!

like image 262
Squirkle Avatar asked Dec 05 '12 06:12

Squirkle


1 Answers

I can answer my own question here. The type of functionality I needed here could be achieved the following way:

var suffix_pattern = new RegExp('\/?' + config.history_root + '\/?','i');

// if IE
if (!Modernizr.history) {

    // initialize router/Backbone.history, but turn off route parsing,
    // since non-window.history parsing will look for a hash, and not finding one,
    // will break our shit.
    Backbone.history.start({ silent: true, hashChange: true });

    // convert any post-# elements to a standard URL to be parsed by our router
    var subroute = window.location.hash.replace('#', '/').split('?')[0],
           route = window.location.pathname.replace(suffix_pattern, '') + subroute;

    Backbone.history.loadUrl(route);
} else {
    Backbone.history.start({ pushState: true, silent: true });
    Backbone.history.loadUrl(Backbone.history.getFragment().replace(suffix_pattern, '').split('?')[0]);
}
like image 123
Squirkle Avatar answered Nov 20 '22 21:11

Squirkle