web-dev-qa-db-fra.com

Itinéraires dorsaux sans hachage?

J'utilise l'épine dorsale pour un projet en cours. Je me demandais s'il était possible de faire du routage sans hachage #, comme le fait davis.js.

Merci!

47
fancy

Vous devez activer pushState

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

http://backbonejs.org/#Router

http://backbonejs.org/#History

Edit: Comme indiqué dans les commentaires, cela ne fonctionnera que pour les navigateurs qui prennent en charge pushState, les navigateurs qui ne le feront pas retomberont sur la méthode de hachage. Il n'y a aucun moyen de contourner cela, vous pouvez activer le navigateur moderne et vous replier ou simplement utiliser des hachages pour tous les navigateurs.

64
JaredMcAteer

Backbone Boilerplate a un excellent assistant qui permet le pushstate. Je l'utilise quand je veux parfois contourner mon routeur.

// 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);
  }
});
10
TYRONEMICHAEL