Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone routes without hashes?

I'm using backbone for a current project. I was wondering if it's possible to do routing without hashes #, like davis.js does.

Thanks!

like image 263
fancy Avatar asked Sep 05 '11 15:09

fancy


2 Answers

You need to enable pushState

Backbone.history.start({pushState: true})

http://backbonejs.org/#Router

http://backbonejs.org/#History

Edit: As noted in the comments this will only work for browsers that support pushState, browsers that don't will fall back to the hash method. There is no real way around this, you can enable for modern browser and fall back or just use hashes for all browsers.

like image 193
JaredMcAteer Avatar answered Nov 13 '22 18:11

JaredMcAteer


Backbone Boilerplate has an excellent helper that enables pushstate. I use it when there are times I want to bypass my router.

// Trigger the initial route and enable HTML5 History API support, set the
// root folder to '/' by default.  Change in app.js.
Backbone.history.start({ pushState: true, root: app.root });

// All navigation that is relative should be passed through the navigate
// method, to be processed by the router. If the link has a `data-bypass`
// attribute, bypass the delegation completely.
$(document).on("click", "a[href]:not([data-bypass])", function(evt) {
  // Get the absolute anchor href.
  var href = { prop: $(this).prop("href"), attr: $(this).attr("href") };
  // Get the absolute root.
  var root = location.protocol + "//" + location.host + app.root;

  // Ensure the root is part of the anchor href, meaning it's relative.
  if (href.prop.slice(0, root.length) === root) {
    // Stop the default event to ensure the link will not cause a page
    // refresh.
    evt.preventDefault();

    // `Backbone.history.navigate` is sufficient for all Routers and will
    // trigger the correct events. The Router's internal `navigate` method
    // calls this anyways.  The fragment is sliced from the root.
    Backbone.history.navigate(href.attr, true);
  }
});
like image 21
TYRONEMICHAEL Avatar answered Nov 13 '22 17:11

TYRONEMICHAEL