I have a jQuery question:
I have an “ADD” button that adds text to the database via AJAX call ($.post()…). The problem is, items are getting repeatedly added. For example:
After page loads: User clicks “ADD” button:
- the first time, it adds an item.
- a seconds time, it adds an item and then adds it again (total 2 items)
- a thrid time, it adds an item and then adds it again and than again (total 3 items)
- etc…
This is a problem as the data is duplicating.
I’ve narrowed down the problem:
$(document).ready(function()
{
// set event handler for Add button
bindAddButtonEventListener();
});
// set event handler for Add button
function bindAddButtonEventListener()
{
// event handler for the add button
$("#addRecord").click(function()
{
openPopUpBox();
enablePopUpBoxControls();
// event handler for Submit button on admin Popup box. Submits data to database
$("#editPopUp #submitChanges").click(function(event)
{
addNewRecord();
});
});
}
// this method will submit a new record to the server, using AJAX post
function addNewRecord()
{
var obj = buildJSONobject();
$.post("admin/addRecordToDatabase", obj, function(data)
{
displayServerValidation(data);
cancelPopUpChanges();
getCatagoriesItems();
});
disablePopUpBoxControls();
}
// this unbinds the events for the popup box controls
function disablePopUpBoxControls()
{
// unbind event handler for button
$("#editPopUp #submitChanges").unbind("click", bindEditButtonEventListener);
//$("#editPopUp #submitChanges").unbind("click", bindAddButtonEventListener);
// unbind event handler for button
$("#editPopUp #cancelEdit").unbind("click", enablePopUpBoxControls);
}
For some reason, inside bindAddButtonEventListener(), when this code runs:
$("#editPopUp #submitChanges").click(function(event)
{
addNewRecord();
});
addNewRecord() is called again the second time and a third time, the third time and then again. I can’t figure out how to stop it from doing it. I thought that unbinding would help, but it doesn’t seem to. Any help would be much appreciated.
Your main problem is here:
This doesn’t actually unbind anything, because it wasn’t ever bound to that function, for example:
This binds an anonymous function (key point being you can’t reference it like you want later), instead since you’re not using
event, bind it directly, like this:Then when you call
.unbind()you need to again reference that function:That’s the fix, as for the “why?”…well since it wasn’t being unbound, it was just racking up a new event handler each time. Every time you clicked
#addRecord, it was adding another save handler on the#editPopUpand#submitChangeselement click events, properly unbinding as I have above should prevent this.