Backbone.js and pushState

Backbone.js and pushState

本文关键字:pushState and js Backbone      更新时间:2023-09-26

如果我在骨干路由器中启用pushState,我需要在所有链路上使用return false,还是骨干会自动处理?有没有样本,包括html部分和脚本部分。

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

使用它,而不是单独对链接执行preventDefault,您可以让路由器在默认情况下处理它们,并通过具有data-bypass属性来进行异常处理。根据我的经验,这是一种很好的模式。我不知道有什么好的例子,但自己尝试一下应该不会太难。Backbone的美丽在于它的简洁;)

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

match()startsWith()(ES 6)也可用于检查协议。如果您想通过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();
  }
}

您可以防止在html中点击<a>标记的默认行为。只需在<script />标签中添加以下代码即可。

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