【问题标题】:Underscore.js templates in backbone.js adding a div around a tr在主干.js 中的 Underscore.js 模板在 tr 周围添加一个 div
【发布时间】:2011-11-14 10:15:03
【问题描述】:

我正在使用来自主干.js 的 underscore.js 的模板功能,我在我的页面中定义了以下模板,如下所示:

<script type="text/template" id="businessunit_template">
  <tr data-uid="{{Uid}}">
    <td class="first"><span>{{Name}}</span></td>
    <td class="{{StatusClass}} tac">{{OverallScore}}%</td>
    <td>
        <a class="impactanalysis individualBu" href="#"> </a>
    </td>
  </tr>
</script>

我将 trs 附加到下表的 tbody 元素:

<table class="listing">
  <thead>
    <tr>          
      <th class="first">Business Units</th>
      <th>BCMS<br />Status</th>
      <th>View</th>
    </tr>
  </thead>
  <tbody id="reportBusinessUnits"></tbody>
</table>

呈现 tr 的个人主干视图如下所示:

class ReportBusinessUnitView extends MIBaseView
  initialize: (options) ->
    @vent = options.vent
    @template = _.template($('#businessunit_template').html())

  events:
    "click .individualBu": "showBusinessUnitDetail"

  showBusinessUnitDetail: (e) =>
    e.preventDefault()    
    self = @   

    @vent.trigger('management:showbusinessunitdeail', @model)

  render: =>
    $(@el).html(@template(@model.toJSON()))
    @

问题是,渲染的输出在 tr 周围有一个 div,我不知道它来自哪里:

<div>
  <tr data-uid="a5e3c218-1ca4-4806-b27e-24a25ed83ab6">
    <td class="first"><span>Central Networks</span></td>
    <td class="red tac">4%</td>
    <td>
        <a class="impactanalysis individualBu" href="#"> </a>
    </td>
  </tr>
</div>

我只是看不出我做错了什么。有人知道这可能来自哪里吗?

【问题讨论】:

标签: backbone.js underscore.js


【解决方案1】:

这看起来很像当您没有在View 中正确声明.el 属性时得到的那种错误的DOM 片段。我会在ReportBusinessUnitView.render() 中放置一个断点/debugger 语句并从那里检查this.el 属性的值。 (View.el 文档)。

另外,请检查您的代码:

  • 您是否声明了.el 属性? (以MIBaseView 为例)
  • 它是否命中了正确的 DOM 节点?

如果没有,Backbone 会自动为您创建 DIV 节点,这可能会造成混淆。

【讨论】:

  • 谢谢一百万,我以为我快疯了。如果我将 tagName: "tr" 添加到视图并从模板中删除封闭的 那么一切都很好。
【解决方案2】:

我相信,在模板周围包含一个默认的 DIV 标记是一种安全措施。这给出了一个父标签,视图的事件被附加到该标签上。这样,事件传播将按预期工作。同样,如果您丢弃视图并删除插入的 HTML,所有事件都会随之发生,从而允许垃圾收集器完成其工作。

我最近非常悲痛,因为我将 .el 设置为静态 HTML 父节点(为了防止添加默认 DIV)。因为即使在我的动态 HTML 被替换后它仍然存在,所以事件仍然围绕着响应操作并造成一般混乱!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2023-03-26
    相关资源
    最近更新 更多