Reputation: 1633
I have this "comment" template:
<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>
With this comment.js file associated (only showing the events part here):
Template.comment.events({
"click #reply-btn": function(e, template){
console.log("Got in.")
$(".reply-to-comment-"+template.data._id).toggle();
}
});
Now, everytime I click reply it should open the reply form for that specific comment, as placed by the template above.
This works, but only on the "root" comments, meaning: if I click reply on a reply that is a reply to a "root" comment, the console.log("Got in.")
will trigger 3 times. If it's a 5 level deep reply it will trigger 5 times, etc.
I suspect the reason for this is the fact that I'm rendering the template "comment" inside the template "comment". As such there's many "events" for which meteor is listening...
But I don't see how I could do it any other way. So, anyone knows a fix for this issue, or a better way to achieve what I'm looking for?
Upvotes: 2
Views: 80
Reputation: 4094
It might be something different, but all your comments have 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.
Behaviour of elements with same id is not well-defined and may lead to problems like this.
Upvotes: 1
Reputation: 4049
Your reasoning is correct - the nested template is registering the event multiple times on those elements causing the issue. I think you can use event.stopPropagation()
to stop the event from bubbling up.
Upvotes: 2