简体   繁体   English

Backbone.js和pushState

[英]Backbone.js and pushState

If I enable pushState in the backbone router, do I need to use return false on all links or does backbone handle this automatically? 如果我在骨干路由器中启用pushState,是否需要在所有链路上使用return false或者骨干是否自动处理? Is there any samples out there, both the html part and the script part. 那里有任何样本,包括html部分和脚本部分。

This is the pattern Tim Branyen uses in his boilerplate : 这是Tim Branyen在他的样板中使用的模式:

initializeRouter: function () {
  Backbone.history.start({ pushState: true });
  $(document).on('click', 'a:not([data-bypass])', function (evt) {

    var href = $(this).attr('href');
    var protocol = this.protocol + '//';

    if (href.slice(protocol.length) !== protocol) {
      evt.preventDefault();
      app.router.navigate(href, true);
    }
  });
}

Using that, rather than individually doing preventDefault on links, you let the router handle them by default and make exceptions by having a data-bypass attribute. 使用它,而不是单独对链接执行preventDefault,您可以让路由器默认处理它们,并通过具有data-bypass属性来实现异常。 In my experience it works well as a pattern. 根据我的经验,它作为一种模式很有效。 I don't know of any great examples around, but trying it out yourself should not be too hard. 我不知道周围有什么好的例子,但是自己尝试一下不应该太难。 Backbone's beauty lies in its simplicity ;) Backbone的美丽在于它的简洁;)

 $(document.body).on('click', 'a', function(e){
   e.preventDefault();
   Backbone.history.navigate(e.currentTarget.pathname, {trigger: true});
 });

match() or startsWith() (ES 6) also can be used for checking protocol. match()startsWith() (ES 6)也可用于检查协议。 If you want to support absolute urls by pathname property, check the base urls by location.origin . 如果要通过pathname属性支持绝对URL,请通过location.origin检查基本URL。

function(evt) {
  var target = evt.currentTarget;
  var href = target.getAttribute('href');

  if (!href.match(/^https?:\/\//)) {
    Backbone.history.navigate(href, true);
    evt.preventDefault();
  }
  // or

  var protocol = target.protocol;

  if (!href.startsWith(protocol)) {
    // ...
  }
  // or

  // http://stackoverflow.com/a/25495161/531320
  if (!window.location.origin) {
    window.location.origin = window.location.protocol 
     + "//" + window.location.hostname
     + (window.location.port ? ':' + window.location.port: '');
  }

  var absolute_url = target.href;
  var base_url = location.origin;
  var pathname = target.pathname;

  if (absolute_url.startsWith(base_url)) {
    Backbone.history.navigate(pathname, true);
    evt.preventDefault();
  }
}

You can prevent the default behavior of click on <a> tags in html. 您可以阻止点击html中<a>标签的默认行为。 Just add the below code inside <script /> tag. 只需在<script />标记内添加以下代码即可。

<script>
$(document).on("click", "a", function(e)
{
    e.preventDefault();
    var href = $(e.currentTarget).attr('href');
    router.navigate(href, true);router
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM