Backbone router getting history length for back-button

二次信任 提交于 2019-12-22 00:33:19

问题


I'm using Backbone inside a PhoneGap application. Like every mobile app I need a back-button functionality. It's basically working perfectly with Backbone, because I can simply use window.history.back() and it just works.

The only problem I have is to decide when to display the back button. Using window.history.length does not work, because it's not decremented when using back() (of course, because you can go forward() as well).

Is there any way to detect if there's more history or if I'm already at the bottom of the stack? Since the browser doesn't seem to supply this info (How to check if the user can go back in browser history or not) does Backbone keep track of this maybe?


回答1:


You can implement something like this pretty easily

Backbone.history.length = 0;
Backbone.history.on('route', function () { ++this.length; });
myRouter.back = function () {
  Backbone.history.length -= 2;
  window.history.back();
};

And just use myRouter.back() to go back.




回答2:


Casey Foster's answer looks nice on first sight, but has a flaw: When using router.navigate with trigger and replace both set to true you'll end up with a wrong counter.

I came up with a much simpler solution: Basically there's only one route where I don't need a back-button and that's the index route. Thus my code now looks like

Backbone.history.on('route', _.bind(function(router, route) {
    if(route === 'index') {
        this.$el.removeClass('has-back-button');
    } else {
        this.$el.addClass('has-back-button');
    }
}, this));



回答3:


Building on @CaseyFoster's answer, you can keep track of the history yourself. In addition to your own back button you need to catch the device's hardware Back-button press.

PhoneGap provides the backbutton event for this:

document.addEventListener("backbutton", function() {
  Backbone.history.length -=2;
}, false);

Notice that Backbone.history.length is defined in Casey Foster's answer, it's not a part of Backbone itself.



来源:https://stackoverflow.com/questions/14606634/backbone-router-getting-history-length-for-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!