Preventing full page reload on Backbone pushState

后端 未结 5 984
夕颜
夕颜 2020-12-09 05:21

I\'m trying to prevent full page reloads using Backbone\'s pushState. When I call navigate() from my view\'s event, I see the messages marked // 1 below, but not // 2. In ad

5条回答
  •  有刺的猬
    2020-12-09 05:59

    to stop the page reload when a user clicks a link, you have to call e.preventDefault() like you were suggesting.

    
    MyView = Backbone.View.extend({
      events: {
        "click .some a": "clicked"
      },
    
      clicked: function(e){
        e.preventDefault();
        // do your stuff here
      }
    });
    

    you're also right that this isn't documented in the backbone docs. events are handled by jQuery, though. so you can assume that any valid jQuery things you would do - such as have an e parameter to an event callback - will work with backbone's events.

    as for this:

    in addition, when I try to open the same tab, the page reloads again.

    are you saying when a user opens a new browser tab to your site's url? if so, then there's nothing you can do about this. when the browser opens the tab it makes the request to the server to load the page.

    if you're referring to a "tab" as part of your site's user interface, though, then the use of e.preventDefault() on your link / "tab" clicks should take care of that.

提交回复
热议问题