我正在尝试使用Backbone从远程API解析JSON数据。这是我到目前为止所得到的:
// --------------------------------------------------
// MODELS
// --------------------------------------------------
var VideoModel = Backbone.Model.extend({
idAttribute: '_id',
parse: function(){
this.id = response._id;
}
});
var videoModel = new VideoModel({ parse:true });
// --------------------------------------------------
// COLLECTIONS
// --------------------------------------------------
var VideosCollection = Backbone.Collection.extend({
model: VideoModel,
url: 'redacted',
parse: function(response){
this.videos = response.data;
this.cid = response.cid;
return response.data;
},
render: function(){
this.collection.forEach(this.addone, this);
}
});
var videosCollection = new VideosCollection();
videosCollection.fetch({
success: function(videos){
console.log('success!');
},
error: function(){
console.log('failed.');
}
});
// --------------------------------------------------
// VIEWS
// --------------------------------------------------
var VideoView = Backbone.View.extend({
template: _.template('<%= videoModel.id %>'),
render: function(){
this$el.html(this.template(this.model.attributes));
return this;
}
});
var videoView = new VideoView({});
var VideosCollectionView = Backbone.View.extend({});
var videosCollectionView = new VideosCollectionView({
collection: videosCollection,
render: function(){
this.collection.forEach(this.addOne, this);
},
addOne: function(videoModel){
this.$el.append(videoView.el);
}
});
我遇到的问题是console.log(videoModel.id)仍为undefined
。
数据是视频的播放列表,是有效的JSON:
{
"total":24,
"per_page":24,
"current_page":1,
"last_page":1,
"from":1,
"to":24,
"data":[
{
"_id":"55d1bb50140ba04c1d8b4583",
对于正确方向的一些提示感到高兴 - 特别是因为我今天早上工作然后......恢复到以前的版本而没有保存。
由于
答案 0 :(得分:1)
来自parse方法的文件:
该函数传递原始响应对象,并应返回 属性hash要在模型上设置。默认实现是 无操作,只需通过JSON响应。
所以默认情况下它的工作原理如下:
parse: function(data) {
return data;
}
您的代码现在不返回任何内容,模型也不会返回任何数据。
我认为您要设置id
属性,但您已经使用idAttribute
设置了_id
属性,并且数据中有_id
,所以它应该可以正常工作解析一下。尝试删除它。
答案 1 :(得分:0)
答案是我试图通过Collection而不是Model来解析。所以我永远不会得到我想要的id。出于某种原因。
我需要将URL移动到模型中并从那里解析:
var VideoModel = Backbone.Model.extend({
idAttribute: '_id',
url: 'redacted',
parse: function(response){
var id = response._id;
var cid = response.cid;
return response.data;
},
}),
现在当我在控制台中执行videoModel.get(1)
时,它会返回数组中第一项的值。