当我创建 View 主干时,如果没有设置 el,则会创建空的 div 容器。模板 (this.$el.html(this.template(this.model.toJSON())))
插入到那个 div 中。如何避免这种包装?我需要没有任何包装的干净模板,以便我可以将它插入任何我想要的地方?用很多元素调用 jobView.$e.children()
是不合理的。
<script id="contactTemplate" type="text/html">
<div class="job">
<h1><%= title %>/<%= type %></h1>
<div><%= description %></div>
</div>
</script>
var JobView = Backbone.View.extend({
template:_.template($("#contactTemplate").html()),
initialize:function () {
this.render();
},
render:function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var jobView = new JobView({
model:jobModel
});
console.log(jobView.el);
最佳答案
我认为这个问题的真正答案还没有提供,只需从模板中删除 div
并将 className
属性添加到 JobView
!这将产生您需要的标记:
模板:
<script id="contactTemplate" type="text/html">
<h1><%= title %>/<%= type %></h1>
<div><%= description %></div>
</script>
View :
var JobView = Backbone.View.extend({
className: 'job', // this class will be added to the wrapping div when you render the view
template:_.template($("#contactTemplate").html()),
initialize:function () {
this.render();
},
render:function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
当您调用 render
时,您将得到所需的标记:
<div class="job">
<h1><%= title %>/<%= type %></h1>
<div><%= description %></div>
</div>
关于javascript - 如何避免在 Backbone 中使用空 div 进行模板包装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13601966/