2012-03-02 44 views
3

目前正在構建一款在手機上運行的應用程序 與手頭問題無關,但通過某個事件 該應用程序登陸狀態,無論是在線還是離線(互聯網手機上可用的或不)Backbone.js我如何根據特定應用程序狀態定義一組自定義路線

離線應用程序是隻有非常有限的,只有少數屏幕)

現在如果你追我做一些愚蠢的事或東西阻止我,我可以更好, 但我的第一個想法是讓路由器有一組動態的路線,

很像您可以在集合上定義動態url屬性。

因此,不是這樣的:

var router = Backbone.Router.extend({ 
    routes: { 
     '' : 'homeAction', 
     'categories' : 'categoriesAction', 
     ... 
    }, 
    homeAction: function(){ }, 
    categoriesAction: function(){ } 
}); 

我想的是這樣的:

var router = Backbone.Router.extend({ 
    initialize: function(){ 
     this.on('app:togglestate', this.toggleRoutes, this); 
    }, 
    toggleRoutes: function() { 
     var router = this; 
     if(App.onlineModus) 
      router.routes = { /* hash with online routes here */ }; 
     else 
      router.routes = { /* hash with offline routes here */ }; 
    }, 
    routes: { 
     '' : 'homeAction', 
     'categories' : 'categoriesAction', 
     ... 
    }, 
    homeAction: function(){ }, 
    categoriesAction: function(){ } 
}); 

儘管這aparently打破了整個應用程序, 爲Backbone.history.start();引發錯誤,無法從通話功能開始未定義。 使我相信我的路由對象在初始化時不知何故被使用,並且無法在運行中改變。

我可能想到遠嗎? 我應該通過其他方式實現嗎?

其他的想法的,我不得不爲:

  • 具有完全一樣的網址,在那裏路由參數是返回一個哈希函數的路線,沒有工作或者
  • ,現在我想完全如果應用程序在每個路由的Action中處於聯機或脫機狀態,則會有不同的測試方式。雖然這似乎太mutch我可能不得不通過一個單一的動作,只傳遞給實際行動,如果路線可以在離線方式訪問所有他們全部?但我真的不知道如何開始這樣一箇中繼行動,沒有寫出太難以置信的樣板代碼...
+0

我很擔心,所以我需要看看其他兩個選項之一,或者通過網關動作傳遞所有動作以首先通過此測試,或者我需要切換兩個路由器對象。 你可以動態卸載路由器中的應用程序執行嗎?我會先嚐試一下我的想法。 – Sander 2012-03-02 06:11:28

回答

1

爲了動態更新路由,您需要在更新路由之後調用_bindRoutes()。

例如:

toggleRoutes: function() { 
    var router = this; 
    if(App.onlineModus) 
     router.routes = { /* hash with online routes here */ }; 
    else 
     router.routes = { /* hash with offline routes here */ }; 

    // Get rid of previous navigation history 
    if(Backbone.history){ 
     Backbone.history == null; 
    } 

    // Bind the new routes 
    router._bindRoutes(); 
} 

注意,當你動態地改變歷史不再有效,所以你需要刪除以前的歷史路線。當調用_bindRoutes時,它會在調用this.route時自動實例化一個新的Backbone.history。

+0

這是一個工作的例子,雖然有點黑客,因爲你調用了一個n _函數,它應該將其標記爲私有。它不應該被直接調用。雖然你是對的,但如果你不介意使用這個黑客,這是一個完美的工作解決方案。感謝你的回答! – Sander 2012-06-29 09:51:11

0

我不得不做很類似的事情。我沒有在我面前的代碼,但是這應該是對周圍我所做的:(編輯:充實出來了一點,所以實際上你可以立即運行)

ApplicationRouter = Backbone.Router.extend({ 
    //some stuff 
    constructor: function (routes) { 
     this.routes = routes; 
     Backbone.Router.prototype.constructor.call(this); 
    } 
}); 

routeObject = { 
    "help": "help" 
} 

ApplicationRouter.instance = function(routes) { 
    if (!this._instance) { 
     this._instance = new ApplicationRouter(routes); 
    } 
    return this._instance; 
} 
ApplicationRouter.instance(routeObject); 
ApplicationRouter.instance().on('route:help', function() { 
    console.log('helped'); 
}); 
Backbone.history.start(); 
//now go to page#help - the console will say "helped" 

從此出,當我需要訪問應用程序路由器時,我只引用了ApplicationRouter.instance()。