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

时间:2013-02-13 18:28:25

标签: backbone.js browser-history

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

来做到这一点

问题是,如果用户通过在浏览器中输入网址直接从其他网址(如google)转到该网页(应用#设置),我想将用户重定向到主页(app /)而不是回到谷歌。

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

这可能吗?

2 个答案:

答案 0 :(得分:24)

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

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

答案 1 :(得分:3)

我使用了来自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。

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

第三个:如果用户是他开始的地方并被送回" home",请设置routesHit = 0,然后重定向到" home" routesHit将再次为1。