简体   繁体   English

骨干路由 - 检测浏览器后退按钮

[英]backbone routes – detecting browser back button press

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. 我真的不确定如何检测此页面更改。

You can bind a callback to Backbone route event: 您可以将回调绑定到Backbone route事件:

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

You can use Backbone.history.getFragment() to know were you are standing. 您可以使用Backbone.history.getFragment()来了解您的身份。

When the back button is pressed a popstate event is triggered. 按下后退按钮时,将触发popstate事件。

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

you can extend the Backbone.Router and overload the route and the open method. 你可以扩展Backbone.Router并重载routeopen方法。 You have all page changings handled in those two methods. 您可以在这两种方法中处理所有页面更改。 So just recopy them from the backbone file, and play with it. 所以只需从骨干文件中重新复制它们,然后使用它。

Obviously even GitHub does not know how to detect which button was pressed ;) They use this code: 显然,即使GitHub也不知道如何检测按下了哪个按钮;)他们使用这段代码:

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))
} 

You should use Backbone.Router and make sure that you don't forget about Backbone.history.start() when starting your application. 您应该使用Backbone.Router并确保在启动应用程序时不要忘记Backbone.history.start()

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. UPD:我们的想法是,当你的网址发生变化时,骨干网的路由器会触发绑定方法。 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. 也许它不是非常自动的方式,它需要编写一些代码,但我认为它应该工作。

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

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