在同一个模板中多次触发事件

Event firing multiple times inside the same template

我有这个 "comment" 模板:

<template name="comment">
  <li class="comment" id="{{_id}}" >

    <div class="comment-wrapper level-{{level}}-comment">
      <span id="reply-btn" class="reply-btn reply-btn-{{_id}}"><a href="#">reply</a></span>
      <div class="content">
        <p>{{body}}</p>
      </div>
    </div>

    <div class="reply-to-comment reply-to-comment-{{_id}}" style="display:none;">
      <form name="reply" class="reply-form">
          <label for="reply_body">Reply to this comment</label>
          <textarea name="reply_body"></textarea>
          <button type="submit" class="btn">Post reply</button>
      </form>
    </div>

    {{#if showChildComments}}
      <ul class="comment-children comment-list">
        {{#each childComments}}
          {{> comment this}}
        {{/each}}
      </ul>
    {{/if}}

  </li>
</template>

与此 comment.js 文件关联(此处仅显示事件部分):

Template.comment.events({
  "click #reply-btn": function(e, template){
    console.log("Got in.")
    $(".reply-to-comment-"+template.data._id).toggle();
  }
});

现在,每次我点击回复时,它都应该打开该特定评论的回复表单,如上面的模板所放置的那样。

这有效,但仅适用于 "root" 评论,意思是:如果我点击回复 "root" 评论的回复,console.log("Got in.") 将触发 3次。如果是5级深度回复会触发5次,以此类推

我怀疑这是因为我在模板 "comment" 内渲染模板 "comment"。因此,有许多 "events" 流星正在监听...

但我看不出还有什么其他方法可以做到这一点。那么,有人知道这个问题的解决方法,或者更好的方法来实现我正在寻找的东西吗?

您的推理是正确的 - 嵌套模板在导致问题的那些元素上多次注册事件。我想你可以使用 event.stopPropagation() 来阻止事件冒泡。

可能有些不同,但您的所有评论都有 span#reply-btn

The id attribute specifies a unique id for an HTML element (the id attribute value must be unique within the HTML document).

The id attribute can be used to point to a style in a style sheet.

The id attribute can also be used by a JavaScript (via the HTML DOM) to make changes to the HTML element with the specific id.

具有相同 id 的元素的行为定义不明确,可能会导致这样的问题。