Reputation: 147
I have a little problem with calling the 'click' function in input object. function assigns an event to the input:
function v_start() {
$('#next').click(function(){
v_check();
});
}
now in javascript files name.js and name2.js i have: Copy code
$(function(){
v_start();
});
is just an example, but in this case the function v_check will be called twice in one click input. is a condition or way to made the event only once ? why the second event will not overwrite?
Upvotes: 0
Views: 3349
Reputation: 1454
Use:
$( ".mybutton" ).off('click').on('click', function() {
// same code
});
This is the best solution for me, or too
$(".mybutton").unbind("click",myFunction).bind("click",myFunction)
Upvotes: 1
Reputation: 193261
Since you call v_start
twice in each of the files obviously you bind your event twice. You can do a simple check if click
event is already handled like this:
function v_start() {
var $next = $('#next');
$next.data('events').click || $next.click(v_check);
}
Upvotes: 1
Reputation: 20155
unbind and bind to be sure the event handler is only added once :
$("#mySelector").unbind("click").bind("click",myFunction)
if there are multiple event listeners :
var myFunction = function(e){ /// my code }
$("#mySelector").unbind("click",myFunction).bind("click",myFunction)
Upvotes: 3
Reputation: 53319
Every time you handle an event in jQuery, it adds the handler to a list. There is no "overwriting".
A simple solution in this case to avoid having the event be assigned twice is to attach a data flag indicating the event has already been attached, like this for example.
function v_start() {
if (!$('#next').data('click-handled')) {
$('#next').data('click-handled', true).click(function(){
v_check();
});
}
}
(You can also manually get a list of events and check if your function is there, but that's more quite a bit more complicated.)
Upvotes: 1