lun*_*afu 0 backbone.js marionette
我想创建一个包含集合中下拉列表的CompositeView:
我的意见:
var ItemView = Backbone.Marionette.ItemView.extend({
template: '#item-tpl'
});
var CompositeView = Backbone.Marionette.CompositeView.extend({
template: '#comp-tpl',
itemView: ItemView,
itemViewContainer: '#mySelect'
});
Run Code Online (Sandbox Code Playgroud)
我的模板:
<script id = "item-tpl" type="text/template">
<option value="<%= id %>"><%= name %></option>
</script>
<script id = "comp-tpl" type="text/template">
...
<form>
<div class="control-group">
<select id='mySelect'></select>
</div>
</form>
...
</script>
Run Code Online (Sandbox Code Playgroud)
呈现的HTML显示默认的div,它打破了选项列表
<select id="mySelect">
<div>
<option value="5">name 1</option>
</div>
<div>
<option value="6">name 2</option>
</div>
</select>
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点:
<select id="mySelect">
<option value="5">name 1</option>
<option value="6">name 2</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我会使用这种技术:http://jsfiddle.net/c9Lrm/8/
首先简化您的模板:
<script id = "item-tpl" type="text/template">
<%= name %>
</script>
Run Code Online (Sandbox Code Playgroud)
然后,您需要提供有关项目视图的信息,以便使用您想要的数据进行渲染:
var aItemView = Backbone.Marionette.ItemView.extend({
template: '#item-tpl',
tagName: "option",
onRender: function(){
this.$el.attr('value', this.model.get('id'));
}
});
Run Code Online (Sandbox Code Playgroud)
您指定了该tagName属性,因此它不会使用默认div标记进行呈现,而是使用option您需要的标记.然后,当渲染选项时,您需要设置value属性,您可以使用该onRender函数.
最后,这是您的新复合视图:
var aCompositeView = Backbone.Marionette.CompositeView.extend({
template: '#comp-tpl',
itemView: aItemView,
itemViewContainer: "select"
});
Run Code Online (Sandbox Code Playgroud)
我们指定itemViewContainer告诉Marionette在哪里放置我们的项目视图.这样,我们就没有必要重新定义appendHtml.
这个解决方案更加清晰,因为我们使用的是Marionette功能,而不是自己做所有事情......当然,其他解决方案也可以使用.
如果您想了解有关使用Marionette生成正确HTML结构的更多信息,您可能会对我的博文感兴趣:http://davidsulc.com/blog/2013/02/03/tutorial-nested-views-using-骨干网,提线木偶,CompositeView中的/