backbone routes – detecting browser back button pr

2019-01-27 14:23发布

I am trying to find a way to detect when the user has pressed the back / forward button in their browser.

I am using backbone to handle routes, along with backbone to render my views.

The issue is I can not hook into this page change event from anywhere.

I tried putting a log in my initialize function for my views .. but it is not tripped when i use the back button.

I am really not sure how else to detect this page change.

5条回答
一夜七次
2楼-- · 2019-01-27 14:46

you can extend the Backbone.Router and overload the route and the open method. You have all page changings handled in those two methods. So just recopy them from the backbone file, and play with it.

查看更多
Viruses.
3楼-- · 2019-01-27 14:48

You should use Backbone.Router and make sure that you don't forget about Backbone.history.start() when starting your application.

Some useful information can be found here and here

Actually the second link is not an article, but a blog. And the guy who wrote it really seems to know a lot about the topic.

UPD: The idea is that backbone's router fire binded methods when your url changing. So you just should put your logic to this method and this way you will able to track that. Maybe it's non very automatic way, and it will take to write some code but I think it should work.

查看更多
虎瘦雄心在
4楼-- · 2019-01-27 14:50

You can bind a callback to Backbone route event:

    Backbone.history.on('route', function () {
        // Do your stuff here
    });

You can use Backbone.history.getFragment() to know were you are standing.

查看更多
Root(大扎)
5楼-- · 2019-01-27 15:05

When the back button is pressed a popstate event is triggered.

I'm using this piece of code:

// listening for the browser's back button
window.addEventListener('popstate', function(e) {
    router.navigate(Backbone.history.getFragment(), { trigger: true, replace: true });
});
查看更多
霸刀☆藐视天下
6楼-- · 2019-01-27 15:08

Obviously even GitHub does not know how to detect which button was pressed ;) They use this code:

slideTo: function (a) {
      var b = this.pathFromURL(a),
         c = this.frameForPath(b),
         d = $("#slider .frame-center").attr("data-path") || "";
      c.is(".frame-center") || (d == "/" || b.split("/").length > d.split("/").length ?
        this.slideForwardTo(a) : this.slideBackTo(a))
} 
查看更多
登录 后发表回答