I've looked at the post - jQuery click events firing multiple times and why is jQuery click event firing multiple times but I still can't figure out why this is happening.
I'm developing a rails-4.2.9
app and have a custom .js
as follows:
$(function() {
var $addNotificationButton = $('#add-notification-button')
$addNotificationButton.on('click', function()
{
console.log("hi from js")
//Code for launching a dialog
})
});
Now, when the page is first loaded and the button is clicked the first time I see only 1 print statement and see the dialog launching in a new route
. When I close the dialog and re-click the button I can see 2 print statements on the console, next time 3 and so on and so forth.
My .js
is put in Application.js
and on the console I see one print statement from Application.js
but the others which are getting tacked on are from VM-2058.js
in Chrome
and from foundation.js
in Firefox
. I'm not sure where or how these are popping up.
My questions are:
1) Why is this happening? I thought that the print statement will get executed only on the button click. Is that not how the jquery
event handler works?
2) Although I can prevent it using one
instead of on
, one of my colleagues mentioned that we shouldn't be using one
since it unbinds the event from the button after the first click and instead look into only loading the .js
needed by the controller
. Now that does work too but is this how we should be doing it? I realize that this is a more rails assets
related question.
My application.js
looks like this:
//= require_tree .
//= require ./notification (refers to the .js file above)