Javascript 没有散​​列的骨干路由?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7310230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:43:47  来源:igfitidea点击:

Backbone routes without hashes?

javascriptbackbone.js

提问by fancy

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

我正在为当前项目使用主干。我想知道是否可以#像 davis.js 那样在没有 hash 的情况下进行路由。

Thanks!

谢谢!

回答by JaredMcAteer

You need to enable pushState

您需要启用 pushState

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

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

http://backbonejs.org/#Router

http://backbonejs.org/#Router

http://backbonejs.org/#History

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.

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

回答by TYRONEMICHAEL

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

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);
  }
});