我正在努力学习 Backbone.js我现在在 this page 上使用了这个例子从集合创建 View 。为此,我使用了一个集合:
var ContactEventCollection = Backbone.Collection.extend({
initialize: function(models, options) {
this.id = options.id;
this.lastContactEventId = options.lastContactEventId;
},
url: function() {
return 'ticket/' + this.id + '/contact-events/' + this.lastContactEventId;
}
});
对话 View 和联系事件 View (联系事件基本上是一条消息):
var ConversationView = Backbone.View.extend({
render: function(){
this.collection.each(function(contactEvent){
var contactEventView = new ContactEventView({model: contactEvent});
this.$el.append(contactEventView.render().el);
}, this);
return this;
}
});
var ContactEventView = Backbone.View.extend({
template: _.template($('#contact-event-template').html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
引用 #contact-event-template
看起来像这样:
<script type="text/template" id="contact-event-template">
<div class="user-message"><%= text %></div>
</script>
然后我尝试将它附加到这个 div ( <div id="put-conversation-here">put the conversation here!</div>
):
var contactEventCollection = new ContactEventCollection([], {id: 1, lastContactEventId: 0});
contactEventCollection.fetch();
console.log(contactEventCollection);
var conversationView = new ConversationView({collection: contactEventCollection});
console.log(conversationView);
$('#put-conversation-here').append(conversationView.render().el);
在控制台中,我看到 conversationView 如下图所示。奇怪的是我确实有一个集合,而且我确实有一个包含所有这些模型的 View ,但是附加的只是一个空的:<div></div>
(即使是 class="user-message"
也不行)。
我也尝试替换 this.model.toJSON()
使用一个简单的对象:{text: "some text"}
,但无济于事。到现在为止,我完全迷路了,无法获得任何帮助。如果可以的话,我会立即为此悬赏,但不幸的是,我必须等两天才能这样做。
有人知道我这里哪里出错了吗?感谢所有帮助、提示或技巧!
最佳答案
contactEventCollection.fetch();
被称为异步,在获取数据之前,您的 html 正在呈现。
你可能想用
$.when(contactEventCollection.fetch()).done(function(){html population});
关于javascript - 如何在 View 中正确渲染 Backbone Collection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24203034/