没有哈希的骨干路由?

fan*_*ncy 47 javascript backbone.js

我正在使用骨干作为当前项目.我想知道是否可以在没有哈希的情况下进行路由#,就像davis.js那样.

谢谢!

Jar*_*eer 64

您需要启用pushState

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

http://backbonejs.org/#Router

http://backbonejs.org/#History

编辑:如评论中所述,这仅适用于支持pushState的浏览器,不支持的浏览器将回退到哈希方法.没有真正的方法,您可以启用现代浏览器并退回或只使用所有浏览器的哈希.

  • 应该注意,这仅适用于支持History API(现代浏览器)的浏览器.没有历史API支持的浏览器将使用哈希. (7认同)

TYR*_*AEL 10

Backbone Boilerplate具有支持pushstate的优秀帮助器.我有时想绕过我的路由器时使用它.

// 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);
  }
});
Run Code Online (Sandbox Code Playgroud)