【问题标题】:Selective history.back() using Backbone.js使用 Backbone.js 的选择性 history.back()
【发布时间】:2013-01-29 09:45:59
【问题描述】:

我有一个 Backbone 应用程序。我正在使用 Backbone.history 来启用后退按钮。我们有一个页面(设置),它会自动加载需要用户输入的弹出窗口。如果用户选择取消,我想回到上一页。我可以使用 window.history.back() 来做到这一点。

问题是,如果用户通过在浏览器中输入 url 从另一个 url(如 google)直接进入该页面(app#settings),我想将用户重定向到主页(app/)而不是而不是回到谷歌。

我还没有找到任何方法来做到这一点。 Backbone.history 看起来像存储来自浏览器的后退按钮的信息,因此即使它们刚刚到达应用程序,它也有历史记录。我也找不到查看上一个网址的方法。

这可能吗?

【问题讨论】:

    标签: backbone.js browser-history


    【解决方案1】:

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

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

    【讨论】:

    • 这种方法计算每条路线,包括浏览器后退导航。假设我在我的应用程序中导航到 3 条路线,然后 routesHit 将为 3。现在使用浏览器后退按钮不会减少 routesHit(而是增加它),浏览器最终会将您带出您的应用程序。
    【解决方案2】:

    我使用了来自 jevakallio 的相同答案,但我遇到了与评论者 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();
    

    添加的行:

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

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

    第三个:如果用户在他开始的地方并被送回“家”,设置routesHit = 0,然后当重定向到“家”时routesHit将再次为1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 2012-04-27
      • 1970-01-01
      • 2023-01-17
      相关资源
      最近更新 更多