我有这个“评论”模板:
<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 次,依此类推。
我怀疑其原因是我在模板“评论”内渲染模板“评论”。因此, meteor 正在监听许多“事件”......
但我不知道如何以其他方式做到这一点。那么,有人知道这个问题的解决方法,或者更好的方法来实现我正在寻找的东西吗?
最佳答案
您的推理是正确的 - 嵌套模板在导致问题的元素上多次注册事件。我认为您可以使用 event.stopPropagation()
来阻止事件冒泡。
关于javascript - 同一模板内多次触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35135476/