我有一个Backbone App,我从MySQL DB通过RESTful API获取数据。现在我想要获取与特定artist_id相关联的特定视频,但无论我最终选择哪个艺术家,它都会显示所有视频,而在我的控制台中我得到../api/videos/artist_videos/undefined
- 所以不知何故,artist_id没有获得传递过来。
所以我的artistVideo.js看起来像是:
function (App, Backbone) {
var ArtistVideos = App.module();
ArtistVideos.View = Backbone.View.extend({
className: 'artistVideos',
template: 'single_video',
initialize: function() {
this.listenTo(this.model, 'sync', this.render);
},
serialize: function() {
return this.model.toJSON();
},
beforeRender: function(){
$('ul.acmenu li a.selected').removeClass('selected');
$('ul.acmenu li a.artistVideos').addClass('selected');
}
});
ArtistVideos.ArtistVideosModel = Backbone.Model.extend({
urlRoot: '../index.php/api/videos/artist_videos/' + this.artist_id,
defaults: {
"not categorized": [],
"live": [],
"others": []
}
});
return ArtistVideos;
}
然后是我的mainView,artistVideoPage.js,其中包含上述文件:
define([
'app',
'backbone',
'modules/artistImage',
'modules/artistName',
'modules/artistVideos',
],
function (App, Backbone, Artistimg, Artistname, ArtistVideos ) {
var ArtistVideo = App.module();
ArtistVideo.View = Backbone.View.extend({
className: 'artist',
template: 'artistVideoPage',
beforeRender: function() {
var artistimgCollection = new Artistimg.ArtistimgCollection();
artistimgCollection.artist_id = this.artist_id;
this.insertView('.artistImage', new Artistimg.View({collection: artistimgCollection}));
artistimgCollection.fetch();
var artistnameCollection = new Artistname.ArtistnameCollection();
artistnameCollection.artist_id = this.artist_id;
this.insertView('.artistName', new Artistname.View({collection: artistnameCollection}));
artistnameCollection.fetch();
var artistvideosModel = new ArtistVideos.ArtistVideosModel();
artistvideosModel.artist_id = this.artist_id;
this.insertView('.artistVideosDiv', new ArtistVideos.View({model: artistvideosModel}));
artistvideosModel.fetch();
}
});
return ArtistVideo;
});
最后,我有一个控制器,看起来像这样:
ArtistController.prototype.initVideos = function(id) {
this.artistVideosView.artist_id = id;
this.artistNavigation.artist_id = id;
App.useLayout('artistVideoPage', 'artistVideoPage').setViews({
'.videosDiv': this.artistVideosView,
'.artistTopMenu': this.artistNavigation
}).render();
};
我尝试console.log(this.artist_id)
- 它实际上显示了正确的ID,但我仍然得到../api/videos/artist_videos/undefined
有谁知道这里有什么问题?为什么我会获得undefined
?
提前致谢?
答案 0 :(得分:0)
好的,自己解决了!
问题是urlRoot
- 显然它试图立即定义this.artist_id
,但当时它并不存在。所以改成它:
url: function() {
return '../index.php/api/videos/artist_videos/' + this.artist_id;
},
解决了这个问题!