骨干路由器导航和锚定href [英] Backbone Router navigate and anchor href

查看:17
本文介绍了骨干路由器导航和锚定href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在支持主干的应用程序中,我看到代码继续使用 <a href="#foo"></a>,而锚点点击由骨干事件处理程序.

In a backbone-enabled app, I have seen code that continues to use <a href="#foo"></a>, while the anchor click is handled by a backbone event handler.

或者,可以通过以下方式处理到#foo 的导航:

Alternatively, the navigation to #foo can be handled by:

Router.history.navigate("foo");

我相信后者是更好的方法,因为它允许轻松迁移到 HTML5 的 pushState 功能和从 HTML5 的 pushState 功能迁移.如果我们确实使用 pushState,对于不支持 pushState 的浏览器,Backbone 将能够优雅地降级为 #foo.

I believe the latter is the superior approach because it allows easy migration to and from HTML5's pushState functionality. And if we do use pushState, Backbone would be able to gracefully degrade to #foo for browsers that do not support pushState.

由于我对 Backbone 还是个新手,有没有经验丰富、知识渊博的人可以证实情况确实如此?

As I am still new to Backbone, can someone more experienced and knowledgable confirm that this is the case?

推荐答案

我个人启用了 pushState 并使用了 Tim Branyen 的 添加点击处理程序 将所有链接点击发送到navigate 除非他们有data-bypass 属性:

I personally have pushState enabled and use the approach taken in Tim Branyen's backbone-boilerplate of adding a click handler that sends all link clicks to navigate unless they have a data-bypass attribute:

$(document).on("click", "a:not([data-bypass])", function(evt) {
  var href = { prop: $(this).prop("href"), attr: $(this).attr("href") };
  var root = location.protocol + "//" + location.host + Backbone.history.options.root;

  if (href.prop && href.prop.slice(0, root.length) === root) {
    evt.preventDefault();
    Backbone.history.navigate(href.attr, true);
  }
});

这很有效,正如@nickf 提到的那样,您不必使用 hash/hashbang hack,即使对于不支持 pushState 的浏览器也是如此.

This works pretty well and as @nickf mentions has the advantage that you don't have to use the hash/hashbang hack, even for browsers that do not support pushState.

这篇关于骨干路由器导航和锚定href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆