Reputation: 386
I have a weird problem that I am not able to debug.
I have a script with the following relevant functions:
a function events()
that has a jQuery.on('click', callback(event))
event binder inside it. That function gets called every time I add or remove anchors with AJAX, but that's irrelevant for this problem.
a function get_passwords()
which gets jQuery.attr("href")
from anchor $("a.active")
and makes a $.post
to the server with a callback that inserts values into a table upon receiving the data
The function get_passwords()
is called synchronously in the callback(event) function like this:
event.preventDefault(); //prevents a browser navigation
$("a.active").removeClass("active"); //removes active class from all other anchors
$(this).addClass("active"); //adds a class "active" to the anchor that was clicked
get_passwords(); <---- the function in question <--BREAKPOINT #1
The function get_passwords()
contains the following relevant lines:
$.post("url", postData, function(data) { //put received data into table }); <--BREAKPOINT #2
Now, the weird bug is that the get_passwords()
function is called multiple times by the same event listener, and only stops calling that function after an arbitrary, but constant amount of times, every time the click is made on an anchor with the event listener.
I've set the breakpoint in FireBug on the above indicated line, and as I execute the script step by step, all it does is jump between the two breakpoints set above (the part where it calls get_passwords()
and where it executes $.post
, 4 times (always the same amount), up until the 4th time when it actually proceeds with the callback in the $.post
function.
Realizing that there is no way I can ask anyone to read through all the code that I've written, does anyone have any suggestions as to where this bug could be coming from?
Thank you in advance.
EDIT: http://jsfiddle.net/nt3A4/
Upvotes: 0
Views: 3234
Reputation: 386
@epascarello, @nbrooks,
You were both right. I was attaching multiple event listeners, somehow, to the same anchor. Probably got lost due to my poor coding planning (I was making up website features as I went along).
Anyway, I fixed it by pre-pending $("a").off() in the events() function, as to remove any other event listeners that may have been set before. Should of done that from the beginning :/
Thank you all for your answers and your time.
Upvotes: 0