我有一个看起来像这样的集合
[
{
"year": 1868,
....
]
},
{
"year": 1872,
....
},
{
...
}
]
是否可以使用'/year/:year': 'year'
或'/(:year)': 'year'
?
我尝试在主App视图中创建一个查找表,它将年份索引传递给模型视图。我尝试过使用_.map,_.each,_.pluck和_.where但我想我一定是做错了。
Here是一个非骨干视图,看起来像什么。因此导航到/(:year)将直接到那一年,这对应于模型索引
修改:澄清一下,基本上我希望用户能够转到/year/:year
,但:year
值对应于某个模型(参见上文)。在这种情况下,转到/year/1868
,将呈现上述集合中的第一个模型。
编辑#2 :以下是我的应用的样子。
这是路由器 var router = 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;
},
我拿出了一些方法,因为它们不是必需的。
答案 0 :(得分: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();