我已经阅读了this和this问题,但没有帮助。我这样叫fetchRelated:
initialize: function(){
Artist.fetchRelated(
'albums',
{success: this.render}
);
},
render: function(){
this.model.get('albums').each(function(album){
console.log(album);
console.log(album.toJSON());
console.log(album.get('title'));
});
$(this.el).html(this.template({
current_user: App.current_user.toJSON(),
artist: this.model.toJSON(),
albums: this.model.get('albums'),
}));
return this;
},
第一个
console.log(album)
返回正确的有效相册模型及其所有属性,但下一次使用toJSON函数调用log则不正确。它只是返回id。因此,当我尝试在下一个日志中检索专辑的标题时,它将返回未定义的信息。此外,它告诉我无法在模板调用中向艺术家调用toJSON(),因为它是未定义的,即使我只是用它来获取专辑...
我确定这里的问题是我还不习惯使用回调 hell ,但是我不知道如何解决它。
编辑1:
对于集合中的每个专辑,console.log(album)响应都是这样的:
_changing: false
_events: Object
_isInitialized: true
_pending: false
_permitsUsed: 0
_previousAttributes: Object
_queue: Backbone.BlockingQueue
_relations: Array[2]
attributes: Object
artist: child
description: "asdasd"
id: 1
image: ""
release_year: 1950
resource_uri: "/albums/1"
songs: child
title: "asdasd"
changed: Object
cid: "c8"
collection: child
id: 1
__proto__: Surrogate
编辑2:
我尝试过更改从主干关系提供的toJSON函数,但是我不明白为什么这样做可以解决我的问题,因为我有其他模型并且该函数可以正常工作而不会被覆盖。
我尝试从自己的toJSON函数返回
_.clone(this.attributes)
,因为console.log(this.attributes)
提供了正确的响应,但由于某种原因,它返回了相同的结果。artist: Object
id: 1
songs: Array[0]
__proto__: Object
这是我的关系。
relations: [{
type: Backbone.HasMany,
key: 'songs',
relatedModel: SongModel,
collectionType: Songs,
reverseRelation:{
key: 'album'
}
}],
最佳答案
我陷入了同样的问题,我发现您可以使用来访问属性
render: function(){
this.model.get('albums').each(function(album){
album.fetch({
success: function(fetchedAlbum) {
console.log(fetchedAlbum.toJSON());
}
});
});
});
这将以获取的关系打印获取的相册...
我不认为这是解决方案,因为使用主干关系的主要目的是避免此类麻烦。
如果我找到解决方案,它将更新此:D真正的解决方案
关于javascript - 与JSON相关的主干不会呈现所有属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15487524/