Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialIgor Yamshchykov
24,397 PointsjQuery click event bind multiple times ?
I have modal window that is opening on click on some element in the grid
$('#table tbody').on('click', '.btn-edit', editModal);
function editModal() {
var modal = $('#editModal').modal('show');
$('#saveButton').on('click', { modal: modal }, save)
}
function save(){
//implementation here.
}
The problem is I can call this modal multiple times and in editModal the click event is binding more than one time, so then the save method fires multiple times.
I founded one solution for that, is to use
$('#saveButton').off('click').on('click', { modal: modal }, save)
but I think there should be a better way to handle this, could someone help me on that ?
1 Answer

Iain Simmons
Treehouse Moderator 32,302 PointsYou could/should take the binding of the click
event on the #saveButton
out of the editModal
function. That way it only binds the event once, when the script is loaded (same as the binding at the top of your example).
Presumably the #saveButton
is only visible when the modal is showing/visible, but it just has to already exist in the DOM before you bind an event to it.
Also, don't forget to use event.preventDefault
within those functions if you're using a
/hyperlink elements to fire the click
events.
Igor Yamshchykov
24,397 PointsIgor Yamshchykov
24,397 PointsThanks, I have one more question regarding using binding outside the function. If I will take out my binding to the outside of the function is there some way to modify the parameters I pass to the event function from the local scope of editModal function? Or this is a bad approach to deal with such problems ?
Iain Simmons
Treehouse Moderator 32,302 PointsIain Simmons
Treehouse Moderator 32,302 PointsYou can pass data to the function you're binding and access it using the
event
object, as described in jQuery's on() documentation, second example.Hope that helps!