【问题标题】:why extra div is render when m redering a view in backbone.js为什么在主干.js 中渲染视图时会渲染额外的 div
【发布时间】:2011-09-22 13:53:32
【问题描述】:

为什么在backbone.js中重新渲染视图时会渲染额外的div

Backbone.View.extend({
  template :_.template( 
        '<li id="user-<%=user.username%>" class="pp-entry group">'+
            '<img src="i/pp-pic-1.png" class="pp-pic" alt="" />'+
            '<span class="whisper-mode-on hide" title="Whisper mode on"></span>'+
            '<h6 class="pp-name"><%=user.firstname%>&nbsp; <%if(user.lastname!="null"){%><%=user.lastname%><%}%></h6>'+
            '<p id="chat-<%=user.username%>"class="pp-msg"></p>'+
        '</li>'), 
  initialize: function() {
    _.bindAll(this, 'render', 'close');
    this.model.bind('change', this.render);
    this.model.view = this;
  }, 
  // Re-render the contents of the User item.
  render: function() {
    $(this.el).html(this.template(this.model.toJSON()));

                $("#participant-window").prepend(this.el);
}
});

当它得到它时,它是这样渲染的:

<ul id="participant-window" class="scroll-pane" style="overflow: hidden; padding: 0px; width: 357px;">
<div>
<li id="user-ashutosh" class="pp-entry group" style="cursor: default;">
<img class="pp-pic" alt="" src="i/pp-pic-1.png">
<span class="whisper-mode-on hide" title="Whisper mode on"></span>
<h6 class="pp-name">Ashutosh&nbsp; </h6>
<p id="chat-ashutosh" class="pp-msg"></p>
</li>
</div>
</ul>

为什么将 li 插入 div 我应该如何阻止它?

【问题讨论】:

  • 你能显示构造View实例的行吗?

标签: jquery backbone.js jquery-templates


【解决方案1】:

除非您覆盖它,否则 Backbone.View 的 el 属性将被初始化为 div 标记。

所以$(this.el).html(this.template(this.model.toJSON()));会将评估后的模板放入div标签中。

从您的代码示例看来,您实际上想要做的是将this.el 设置为$("ul#participant-window")。那么你在渲染中所要做的就是

render: function() {
    $(this.el).html(this.template(this.model.toJSON()));
}

【讨论】:

    【解决方案2】:

    在这一行:

    $(this.el).html(this.template(this.model.toJSON()));
    

    ...您将this.el 的内容设置为模板输出。如果不知何故 el 成员变量已被初始化为现有的 div 元素,您只需更改它的内容,然后附加到 #participant-window

    或许可以试试:

    this.el = $(this.template(this.model.toJSON())));
    

    【讨论】:

    • 您可能希望在更改 this.el 后使用 this.delegateEvents()。
    • 嗯,我以为你不应该重新分配 el
    • this.setElement($(this.template(this.model.toJSON()))); 似乎是一种更好的方法。 documentcloud.github.com/backbone/#View-setElement
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多