user3142695 user3142695 - 7 months ago 54
Javascript Question

Meteor: multiple event fireing on nested templates

I have a template structure which uses nested templates to display children of each element. That is working so far.

Furthermore I have an event on a icon click (

click .fa-edit
). If I click on that icon in the first level, everything is working, but if I click on a nested element the click results in multiple events, so I get multiple console.log on one click. I don't understand that and therefore I don't know how to prevent that.

main template

<template name="main">

{{#if Template.subscriptionsReady}}

<div id="elements">
{{ > getElements parentId=id }}
</div>

{{else}}
<div class="loading">{{ > spinner }}</div>
{{/if}}

</template>


children template

<template name="getElements">

{{#each children}}
<div class="row">
<input type="text" name="keyword" value="{{value}}"><i class="fa fa-edit"></i>
</div>

{{#if subchilden}}
{{ > getElements parentId=id }}
{{/if}}
{{/each}}

</template>


events

Template.getElements.events({
'click .fa-edit': function(event) {
console.log('click');
}
});

Answer

The issue is that the events are delegated to the outer element in your template.

Since you have nested templates (the same template) when an event is fired it bubbles up to all the outer elements of the parent templates and is caught by them too.

You need to prevent the bubbling of the event

Template.getElements.events({
    'click .fa-edit': function(event) {
        event.stopPropagation(); // add this to stop the event from bubbling any further
        console.log('click');
    }
});