2013-02-13 61 views
9

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

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

我一直无法想出任何方式来做到这一点。 Backbone.history看起来像存储来自浏览器后退按钮的信息,所以即使他们刚刚到达应用程序,它也有历史记录。我也无法找到查看以前的网址的方法。

这可能吗?

回答

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

这种方法统计包括浏览器后退导航在内的所有路线。假设我在我的应用程序内导航到3条路线,那么routesHit将为3.现在使用浏览器后退按钮不会减少routesHit(而是增加它),浏览器最终会将您从应用程序中移出。 – 2013-09-18 08:40:08

3

我用同样的答案从jevakallio,但我有这样的评论者杰伊·库马尔有同样的问题: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}); 
    } 
    } 
}); 

,并使用RO uter方法导航回:

appRouter.back(); 

新增线路:

一日一:从routesHit减去2,那么当其重定向到“返回”页面,它会获得1点所以它实际上是像你这样刚减1。

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

第三个:如果用户是他在哪里开始并且被发送回“家”,设置routesHit = 0,那么当重定向到“家”时routesHit将再次为1。