Goose Goose - 3 months ago 15
Javascript Question

Event handler inside event handler is multiplying

I have this code

jQuery('#parent').on('click', jQuery('#fileInput'), function (e) {
jQuery(e.target).attr('data-fileurl', '');
jQuery('#parent').on('change', jQuery('#fileInput'), function (e) {
usefulFunction(jQuery(e.target);
}
}


The idea is to detect if cancel was chosen on file browse, and it succeeds at that.

The problem is if I click it again, then it will run the
.on('chance')
twice and thus run
usefulFunction
. Each click adds a change event handler.
usefulFunction
should only be run once for each time
jQuery('#fileInput')
is changed. How can I prevent this unexpected behavior?

Answer

You should use one method instead:

jQuery('#parent').one('change', jQuery('#fileInput'), function (e) {
                    ^
...
Comments