我正在尝试学习Backbone.js,为此我现在想要将一组模型加载到视图中。通过在窗口中打开选项卡,我首先添加以下模板:
<script type="text/template" id="tab-content-template">
<div class="conversation-window" id="conversation<%= ticketId %>"></div>
</script>
在这个tempalte中,我现在想要加载属于ticketId的消息集合。所以我制作了这样一个集合:
var MessageCollection = Backbone.Collection.extend({
url: 'ticket/:id/messages'
});
和观点:
var MessageView = Backbone.View.extend({
initialize: function(models, options) {
this.ticketId = options.ticketId;
},
el: function() {
return '#conversation' + this.ticketId;
},
className: 'user-message'
});
所以我希望在#conversation1(对于ticketId 1)中插入消息列表。然后我试着运行这个:
var messageView = new MessageView(messageCollection, {ticketId: 1});
messageView.render();
console.log(messageView);
不幸的是没有任何事情发生,当我查看控制台时,我看到ticketId: 1
但是el: undefined
。我有点迷失在我做错的事情上(总的来说,它在Backbone中丢失了。)
有人知道我在这里做错了什么以及如何解决它?欢迎所有提示!
答案 0 :(得分:0)
我认为这就是你想要的:
<div id = "conversation1">stuff insert here</div>
<script>
var MessageCollection = Backbone.Collection.extend({
// url: 'ticket/:id/messages' //<-- put this in router
});
// you need to create an instance of you collection somewhere and pass in
// models as parameter. note that your ticketId is included in the models:
var messageCollection = new MessageCollection([{ticketId:1,attr:'stuff1'}, {ticketId:2,attr:'stuff1'}])
var MessageView = Backbone.View.extend({
initialize: function(models, options) {
this.ticketId_1 = this.collection.models[0].get('ticketId');
this.ticketId_2 = this.collection.models[1].get('ticketId');
},
// can not reference el and define a <div id="user-message"> simultaneously
/*
el: function() {
return '#conversation' + this.ticketId;
},
*/
className: 'user-message',
render: function() {
$('#conversation'+ this.ticketId_1).html(this.$el.html('stuff from model goes in here'));
}
});
// var messageView = new MessageView( messageCollection, {ticketId: 1});
// the above wouldn't work. your ticketId should be passed into your view via model
// then you associate you view to your collection like so:
var messageView = new MessageView({ collection: messageCollection });
messageView.render();
console.log(messageView.$el.html());
</script>