我在这里查看 Angry Cats Backbone/Marionette 教程帖子
http://davidsulc.com/blog/2012/04/15/a-simple-backbone-marionette-tutorial/
http://davidsulc.com/blog/2012/04/22/a-simple-backbone-marionette-tutorial-part-2/
我遇到了同样的问题/需要张贴在这里:
Backbone.js turning off wrap by div in render
但我只能让它为 Backbone.Views 工作,而不是 Backbone.Marionette.ItemViews。
例如,从上面简单的主干 Marionette 教程链接,拿AngryCatView:
AngryCatView = Backbone.Marionette.ItemView.extend({
template: "#angry_cat-template",
tagName: 'tr',
className: 'angry_cat',
...
});
模板,#angry_cat-template
,看起来像这样:
<script type="text/template" id="angry_cat-template">
<td><%= rank %></td>
<td><%= votes %></td>
<td><%= name %></td>
...
</script>
我不喜欢的是 AngryCatView 需要有
tagName: 'tr',
className: 'angry_cat',
-- 如果我取 tagName
出来,然后 angry_cat-template
被 <div>
包裹.
我想要的是在一个地方指定 HTML(angry_cat 模板)并且在 angry_cat 模板中没有大部分 HTML(所有 <td>
标签)和一点 HTML(<tr>
标签)在愤怒的猫 View 。我想在 angry_cat-template 中写这个:
<script type="text/template" id="angry_cat-template">
<tr class="angry_cat">
<td><%= rank %></td>
<td><%= votes %></td>
<td><%= name %></td>
...
</tr>
</script>
它对我来说感觉更干净,但我一直在研究 Derik Bailey 在“Backbone.js 关闭渲染中的 div 包裹”中的回答,并且无法让它为 Backbone.Marionette 工作。
有什么想法吗?
最佳答案
2014/02/18 — 更新以适应@vaughan 和@Thom-Nichols 在评论中指出的改进
在我的许多 itemView/布局中,我都这样做:
var Layout = Backbone.Marionette.Layout.extend({
...
onRender: function () {
// Get rid of that pesky wrapping-div.
// Assumes 1 child element present in template.
this.$el = this.$el.children();
// Unwrap the element to prevent infinitely
// nesting elements during re-render.
this.$el.unwrap();
this.setElement(this.$el);
}
...
});
以上代码仅在包装器 div 包含单个元素时才有效,这就是我设计模板的方式。
在你的情况下 .children()
将返回 <tr class="angry_cat">
, 所以这应该很完美。
我同意,它确实使模板更加简洁。
需要注意的一点:
此技术不会强制只有 1 个子元素。它盲目地抓取 .children()
因此,如果您错误地构建模板以返回多个元素,例如第一个模板示例 3 <td>
元素,它不会很好地工作。
它要求您的模板返回单个元素,就像您在第二个模板中的根元素一样 <tr>
元素。
当然,如果需要的话,可以编写它来对此进行测试。
Here is a working example for the curious: http://codepen.io/somethingkindawierd/pen/txnpE
关于javascript - 关闭 Backbone.Marionette.ItemView 的 div 换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14656068/