无法获得脊梁事件;将模型渲染到多个位置

时间:2013-09-08 17:07:21

标签: backbone.js

我似乎无法触发事件。

以下是多视图和单视图:

PartyView =  Backbone.View.extend({
tagName: 'span',
className: 'aParty',
senderTemplate: _.template($('#senderTemplate').html()),
recipientTemplate: _.template($('#recipientTemplate').html()),
render: function () {
if (this.model.get("isSender")=="1")
    $("#senders").append(this.senderTemplate(this.model.toJSON()))
else
    $("#recipients").append(this.recipientTemplate(this.model.toJSON()))
},
events: {
    "click .delete":"deleteParty",
    'click #recipients': "sayhi"
},
sayhi : function () { console.log ("hi"); },
deleteParty:function () {
    this.model.destroy();
    this.remove();
}
})

多个:

PartiesView = Backbone.View.extend({
className: "partiesView",
senderTemplate: _.template($('#senderTemplate').html()),
recipientTemplate: _.template($('#recipientTemplate').html()),
render: function(eventName) {
    $("#senders").empty();
    $("#recipients").empty();
  _.each(this.model.models, function(party){
      var partyview = new PartyView ({ model: party })
      partyview.render();
  }, this);

  return this;
},
events : {
'click #recipients': "sayhi"
},
sayhi : function () { console.log ("hi"); }
});

我没有控制台错误,一切都很好。我只是无法获得sayhi或删除事件。我怀疑它与events getting lost in templatingthis similar one最密切相关,但实际上我一直试图弄清楚它几个小时。任何指导将不胜感激!!

编辑1:

这是模板:

<script type='text/template' id='senderTemplate'>
<span class='greenbubble'><%= email%>&nbsp;<button class='delete'>x</button></span>&nbsp;&nbsp;
</script>

<script type='text/template' id='recipientTemplate'>
<span class='lightbluebubble'><%= email%>&nbsp;<button class='delete'>x</button></span>&nbsp;&nbsp;
</script>

编辑2:

#senders#recipients目前位于HTML

<div id='partiesView'>
Senders:<span id='senders'></span><BR>
Recipients:<span id='recipients'></span>
</div>

编辑3:

小提琴中的最终作品!

Final version in fiddle

1 个答案:

答案 0 :(得分:3)

我对#recipients引用持怀疑态度。视图的events属性仅委托视图el内的项目,我在任何视图中都没有看到#recipients。如果#recipients在这两个视图之外,则不会触发。

根据评论进行编辑

你不应该这样做:

$("#senders").append(this.senderTemplate(this.model.toJSON()))

因为您可能正在修改视图$el之外的元素。相反,这样做:

this.$("#senders").append(this.senderTemplate(this.model.toJSON()))

您要绑定的所有元素都应包含在视图$el中。如果他们不是,他们将无法正确绑定。这可能是所有绑定的根本原因,而不仅仅是#recipients