在我想要的地方获取数据时遇到一些麻烦。
在我的路由器中,我有一个传递ID的函数,如下所示:
routes: {
'deck/:id': 'getDeckId'
},
getDeckId: function(id) {
this.loadView(new DeckView())
},
loadView: function(view) {
this.view && (this.view.kill ? this.view.kill() : this.view.remove());
this.view = view;
}
在我的收藏中,我加载了一个JSON文件。对于该URL,我想添加我在路由器中传递的ID。
var DeckCollection = Backbone.Collection.extend({
model: DeckModel,
url: "myUrl"+id, //the id i passing from my router
parse: function (response) {
return response;
},
initialize: function() {
},
return DeckCollection;
});
视图
var DeckView = Backbone.View.extend({
//initialize etc
});
因此,当视图初始化时,我想使用路由器传递的ID加载此JSON。我该怎么做?
答案 0 :(得分:1)
将id传递给DeckView构造函数。
routes: {
'deck/:id': 'getDeckId'
},
getDeckId: function(id) {
this.loadView(new DeckView({deckId: id}))
},
loadView: function(view) {
this.view && (this.view.kill ? this.view.kill() : this.view.remove());
this.view = view;
}
创建将使用id和您的网址的网址
var DeckCollection = Backbone.Collection.extend({
id: '',
model: DeckModel,
url: function () {
return 'myURL' + this.id;
}
});
在视图初始化时设置集合的ID
var DeckView = Backbone.View.extend({
initialize: function (options) {
this.decks = new DeckCollection();
this.decks.id = options.id;
this.decks.fetch();
}
});