【发布时间】:2013-03-18 21:43:47
【问题描述】:
我已经阅读了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。因此,当我尝试在下一个日志中检索专辑的标题时,它会返回 undefined。
另外它告诉我我不能在模板调用中调用 toJSON() 给艺术家,因为它是未定义的,尽管我只是用它来获取专辑...
我确定我的问题在于我仍然不习惯的回调地狱,但我不知道如何解决它。
编辑 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'
}
}],
【问题讨论】:
-
您能发布
console.log(album);调用的结果吗? -
你能发布关系吗?
-
你陷入了 js 绑定陷阱。在您的
initialize函数中,您需要做的第一件事是调用_.bindAll(this)将所有视图方法绑定到this的正确上下文。 -
如果你的观察是正确的,那么
console.log函数或album.toJSON函数会弄乱你的数据(例如你可以'覆盖'toJSON函数,在我们的项目中我们经常这样做)尝试调试它。正如前面的作者所注意到的,绑定你作为回调传递的函数,在你的例子中是_.bindAll(this, 'render'); -
使用 _.bindAll(this, 'render') 并没有解决它,如果我们需要在每个视图中调用它,那为什么它不是默认功能?
标签: javascript backbone.js asynchronous backbone-views backbone-relational