2013-02-27 86 views
1

我有一個集合,它看起來像這樣Backbone.js的路由取決於型號值

[ 
    { 
     "year": 1868, 
     .... 
      ] 
    }, 
    { 
     "year": 1872, 
     .... 
    }, 
    { 
     ... 
    } 
] 

有沒有一種方法來設置是路由與'/year/:year': 'year''/(:year)': 'year'

我已經嘗試在主應用視圖中製作查找表,該查看錶將年份索引傳遞給模型視圖。我曾嘗試使用_.map,_.each,_.pluck和_.where,但我想我必須做錯了什麼。

Here是它的外觀的非骨幹視圖。所以,導航到/(:年)將直接進入那年,相當於一個模型索引

編輯:澄清,基本上我希望用戶能夠去/year/:year,但:year值對應於一個特定的模型(見上文)。在這種情況下去/year/1868,將呈現上述集合中的第一個模型。

編輯#2:這是我的應用程序的樣子。

這是路由器 VAR路由器= Backbone.Router.extend({ 路線:{ '': '根', '年(/:年)': '年' },

root: function() { 
     new App(); 
    }, 

    year: function(year) { 
     new App({ 
      year: year 
     }); 
    } 
}); 

因爲它們非必要的調用該文件

define(['backbone', 'assets/js/collections/elections.js', 'assets/js/views/election.js', 'jqueryui'], function(Backbone, Elections, ElectionView, simpleSlider) { 
var AppView = Backbone.View.extend({ 
    current_election_index: 0, 
    active_btn_class: 'dark_blue_bg', 
    wiki_base: 'http://en.wikipedia.org/wiki/United_States_presidential_election,_', 
    started: 0, 
    el: 'body', 
    playback: { 
     id: '', 
     duration: 1750, 
     status: false 
    }, 

    initialize: function() { 
     elections = new Elections(); 
     _.bindAll(this, 'render'); 
     this.listenTo(elections, 'reset', this.render); 
     elections.fetch(); 
     this.remove_loader(); 
    }, 

    render: function() { 
     if (this.started === 0) { 
      this.election_year(); 
     } 
     var view = new ElectionView({ 
      model: elections.at(this.current_election_index), 
      election_index: this.current_election_index 
     }); 
     this._make_slider(); 
     this.update_ui(); 
     return this; 
    }, 

我拿出一些方法。

+1

你可以嘗試澄清你的問題?從你的解釋中解析有點困難。 – jevakallio 2013-02-27 14:34:51

回答

0

一個典型的解決方案會看起來是這樣的:

var AppRouter = Backbone.Router.extend({ 
    routes: { 
    "year(/:year)" : "electionByYear" 
    }, 

    electionByYear: function(year) { 

    //all of your data, wherever you get it from 
    var results = this.allElectionResults; 

    //if a year parameter was given in the url 
    if(year) { 
     //filter the data to records where the year matches the parameter 
     results = _.findWhere(results, { year: parseInt(year, 10)}); 
    } 

    doSomething(results); 

    } 
}); 

編輯基於評論:如果你的觀點是負責創建收集,應將上面的邏輯移動到您的看法,並簡單地傳遞year參數視圖作爲參數:

var View = Backbone.View.extend({ 
    initialize: function(options) { 
    this.year = options.year; 
    } 
}); 

var view = new View({year:year}); 
view.render(); 

或者,如果您使用的是現有的觀點:

view.year = year; 
view.render(); 
+0

什麼是數據?以及路由器如何在創建時訪問集合?現在'root'路由正在創建視圖,然後調用collections.fetch()。我試着做一個console.log(collection.at(0),我得到'undefined' – alexdmejias 2013-02-28 04:15:45

+0

@ alme1304,抱歉,'data'只是一個輸入錯誤,我打算輸入'results'。 。我也不太確定'collection'的問題是什麼,但是也給了答案一些建議。 – jevakallio 2013-03-01 13:27:46

+0

不確定你要我放置代碼的位置,但我仍然無法使用_。 findWhere,我一直未定義,我還添加了更多的代碼來清除所有內容 – alexdmejias 2013-03-03 01:34:49