2013-02-13 63 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。