如何在主干视图中加载模型集合
How to load Collection of models in Backbone View?
我正在尝试学习Backbone.js,为此,我现在要将模型集合加载到视图中。通过在窗口中打开一个选项卡,我首先添加以下模板:
<script type="text/template" id="tab-content-template">
<div class="conversation-window" id="conversation<%= ticketId %>"></div>
</script>
在这个模板中,我现在要加载一个属于ticketId的消息集合。所以我做了一个这样的集合:
var MessageCollection = Backbone.Collection.extend({
url: 'ticket/:id/messages'
});
和view:
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
。我有点迷失在我做错了什么(有点迷失在骨干一般)。
有谁知道我在这里做错了什么以及我如何解决它吗?欢迎所有的建议!
我想这就是你想要的:
<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>
相关文章:
- 延迟 AngularJS 路由更改,直到加载模型以防止闪烁
- 加载模型与三个.js
- Three.js隐藏已加载模型的对象
- Javascript客户端从ASP.NET MVC后端延迟加载模型
- 如何在三.js中加载 .x 模型
- 如何将内置选项卡与没有路由的 ember 集成,以便为每个选项卡异步加载模型
- 三.js 加载模型时进度加载器不隐藏
- Angularjs:如何在惰性模式下加载模型
- WebGL显示不带矩阵的加载模型
- 单击时重新加载模型
- Ember 2.0路由器不加载模型数据
- 转换到路线后重新加载模型
- 在three.js中加载模型的最简单方法
- 在AngularJS中加载模型并渲染内容后执行函数
- 下划线模板不加载模型.% console.log(Model.id) %>它是未定义的
- 如何在主干视图中加载模型集合
- 从MEAN.IO中的其他包加载模型
- MVC淘汰.儿童下载列表没有't第一时间加载模型数据
- 在模态中加载模型只工作一次
- 烬路线在错误加载模型后卡住