使用Backbone.js选择history.back()

使用Backbone.js选择history.back(),backbone.js,browser-history,Backbone.js,Browser History,我有一个主干应用程序。我正在使用Backbone.history启用“后退”按钮。我们有一个页面(设置),自动加载需要用户输入的弹出窗口。如果用户选择取消,我想返回上一页。我可以使用window.history.back()完成此操作 问题是,如果用户通过在浏览器中键入url从另一个url(如谷歌)直接进入该页面(应用程序设置),我希望将用户重定向到主页(应用程序/),而不是返回谷歌 我还没能想出任何办法来做这件事。Backbone.history看起来像是从浏览器的“后退”按钮存储信息,所以即

我有一个主干应用程序。我正在使用Backbone.history启用“后退”按钮。我们有一个页面(设置),自动加载需要用户输入的弹出窗口。如果用户选择取消,我想返回上一页。我可以使用window.history.back()完成此操作

问题是,如果用户通过在浏览器中键入url从另一个url(如谷歌)直接进入该页面(应用程序设置),我希望将用户重定向到主页(应用程序/),而不是返回谷歌

我还没能想出任何办法来做这件事。Backbone.history看起来像是从浏览器的“后退”按钮存储信息,所以即使他们刚刚到达应用程序,它也有一个历史记录。我也找不到查看上一个url的方法


这可能吗?

用您自己的方法包装后导航逻辑。也许在路由器上:

var AppRouter = Backbone.Router.extend({

  initialize: function() {
    this.routesHit = 0;
    //keep count of number of routes handled by your application
    Backbone.history.on('route', function() { this.routesHit++; }, this);
  },

  back: function() {
    if(this.routesHit > 1) {
      //more than one route hit -> user did not land to current page directly
      window.history.back();
    } else {
      //otherwise go to the home page. Use replaceState if available so
      //the navigation doesn't create an extra history entry
      this.navigate('app/', {trigger:true, replace:true});
    }
  }
});
并使用路由器方法导航回:

appRouter.back();
appRouter.back();

我使用了来自的相同答案,但我遇到了与评论员Jay Kumar相同的问题:
routesHit
没有减法,所以点击
appRouter.back()
足够的时间会让用户退出应用程序,所以我添加了3行:

var AppRouter = Backbone.Router.extend({

  initialize: function() {
    this.routesHit = 0;
    //keep count of number of routes handled by your application
    Backbone.history.on('route', function() { this.routesHit++; }, this);
  },

  back: function() {
    if(this.routesHit > 1) {
      //more than one route hit -> user did not land to current page directly
      this.routesHit = this.routesHit - 2; //Added line: read below
      window.history.back();
    } else {
      //otherwise go to the home page. Use replaceState if available so
      //the navigation doesn't create an extra history entry
      if(Backbone.history.getFragment() != 'app/') //Added line: read below
        this.routesHit = 0; //Added line: read below
      this.navigate('app/', {trigger:true, replace:true});
    }
  }
});
并使用路由器方法导航回:

appRouter.back();
appRouter.back();
新增行:

第一个:从
routesHit
中减去2,然后当它重定向到“back”页面时,它将获得1,所以实际上就像你只做了一个-1

第二个:如果用户已经在“家”,就不会有重定向,所以不要做任何事情来路由它


第三个:如果用户是从哪里开始的,并且正在被发送回“主页”,则设置
routesHit=0
,然后当重定向到“主页”时
routesHit
将再次为1。

此方法统计每个路由,包括浏览器返回导航。假设我在我的应用程序中导航到3条路线,那么routesHit将是3条。现在,使用浏览器后退按钮不会减少路由限制(而是增加路由限制),浏览器最终会将您从应用程序中删除。