Backbone.js and pushState

前端 未结 4 1184
温柔的废话
温柔的废话 2020-11-28 20:19

If I enable pushState in the backbone router, do I need to use return false on all links or does backbone handle this automatically? Is there any samples out there, both the

相关标签:
4条回答
  • 2020-11-28 20:29

    You can prevent the default behavior of click on <a> tags in html. Just add the below code inside <script /> tag.

    <script>
    $(document).on("click", "a", function(e)
    {
        e.preventDefault();
        var href = $(e.currentTarget).attr('href');
        router.navigate(href, true);router
    });
    </script>
    
    0 讨论(0)
  • 2020-11-28 20:45
     $(document.body).on('click', 'a', function(e){
       e.preventDefault();
       Backbone.history.navigate(e.currentTarget.pathname, {trigger: true});
     });
    
    0 讨论(0)
  • 2020-11-28 20:48

    match() or startsWith() (ES 6) also can be used for checking protocol. If you want to support absolute urls by pathname property, check the base urls by location.origin.

    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();
      }
    }
    
    0 讨论(0)
  • 2020-11-28 20:52

    This is the pattern Tim Branyen uses in his boilerplate:

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

    0 讨论(0)
提交回复
热议问题