javascript - 如何避免在 Backbone 中使用空 div 进行模板包装?

标签 javascript jquery backbone.js

当我创建 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/

相关文章:

javascript - Browserify 在多次 require 调用时仅执行一次模块代码

javascript - 如何动态扩展 div 的宽度以适合一个非常长的单词?

javascript - D3js,时间轴标签的特定格式

javascript - 将 php 变量从 Controller 传递到 javascript 函数

javascript - jQuery 获取被点击元素的父 jQuery 对象

javascript - 如何在主干js中获取响应代码?

javascript - 什么正则表达式会检测字符串是否是编号列表的一部分?

javascript - 使用 JQuery 将 <span> 拖放到段落中

javascript - 使用jquery动态添加表格行,然后在每个新行中添加自动填充选择框

javascript - Backbone collection.create : after waiting, 如何接收服务器响应并添加项目?