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

XMe*_*Men 4 jquery jquery-templates backbone.js

为什么在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);
}
});
Run Code Online (Sandbox Code Playgroud)

什么时候它正在渲染它像这样:

<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>
Run Code Online (Sandbox Code Playgroud)

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

sje*_*397 7

在这一行:

$(this.el).html(this.template(this.model.toJSON()));
Run Code Online (Sandbox Code Playgroud)

...您将内容设置this.el为模板输出.如果el某个成员变量已经初始化为现有div元素,那么您只需要更改它的内容,然后附加到#participant-window.

也许试试:

this.el = $(this.template(this.model.toJSON())));
Run Code Online (Sandbox Code Playgroud)

  • `this.setElement($(this.template(this.model.toJSON())));`似乎是一种更好的方法.http://documentcloud.github.com/backbone/#View-setElement (3认同)
  • 您可能希望在更改this.el后使用this.delegateEvents(). (2认同)