【发布时间】:2026-02-05 00:15:01
【问题描述】:
我对 Backbone.js 还很陌生,到目前为止我很喜欢它,但是我在尝试获取要呈现的关系数据时遇到了一些麻烦。
在我的 Backbone 视图(称为 ImagesView)中,我有以下代码:
// Render it
render: function () {
var self = this;
// Empty the container first
self.$el.html("")
// Loop through images
self.collection.each(function(img){
// convert `img` to a JSON object
img = img.toJSON()
// Append each one
self.$el.append(self.template(img))
}, self)
}
集合中有 3 张图片,它们使用上述代码正确模板化。 img 对象中有一个 user 属性,其中包含用户 ID。我正在尝试返回用户的详细信息,并在模板中使用这些而不是 ID。我正在使用以下代码:
// Render it
render: function () {
var self = this;
// Empty the container first
self.$el.html("")
// Loop through images
self.collection.each(function(img){
// convert `img` to a JSON object
img = img.toJSON()
/* New code START */
// Each img has a `user` attribute containing the userID
// We'll use this to get their details
$.getJSON('/user/' + img.user, {}, function(json, textStatus) {
img.photographer = {
id: json.id,
username: json.username,
real_name: json.real_name
}
/* Moved 1 level deeper */
// Append each one
self.$el.append(self.template(img))
});
/* New code END */
}, self)
}
当我这样做时,用户的详细信息被正确返回并插入到模板中,但我现在以完全随机的顺序返回每个图像中的 3 个而不是 1 个(即总共 9 个)。我究竟做错了什么?我愿意使用 Backbone 方法而不是 getJSON,如果这会使它更容易,我只是无法让它自己工作。我使用 underscore.js 作为模板
【问题讨论】:
标签: javascript backbone.js underscore.js