Reputation: 818
Why
JQuery.on('sameEventName.',function(){...});
piles up depending how many time the code works? And is there a way to prevent this??
Here is the fiddle
Upvotes: 0
Views: 142
Reputation: 8207
I guess you want to achieve behaviour where even with multiple clicks, only 1 event listener is present. Although the following it's not ideal, but it's the most simple workaround. Use .off
function to remove previous event listener.
$(document).off('aCustomEventName');
$(document).on('aCustomEventName', function(){...});
Full snippet:
$('#set').on('click', function () {
$(document).off('aCustomEventName');
$(document).on('aCustomEventName', function (event) {
alert('event caught');
});
});
$('#trigger').on('click', function () {
$(document).trigger("aCustomEventName");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Click on Set Listener button a few times then click on the Trigger Event button..
</div>
<button id="set">Set Listener</button>
<button id="trigger">Trigger Event</button>
And also fixed jsfiddle (same as snippet).
Upvotes: 1