Jquery click () event fired repeatedly

I have a jQuery question:

I have an “ADD" button that adds text to the database via an AJAX call ($ .post () ...). The problem is that items are constantly being added. For instance:

After loading the page: The user clicks the "ADD" button:

  • adds an element for the first time.
  • seconds, adds an item, and then adds it again (total 2 items).
  • for a short time adds an element, and then adds it again and again (only 3 elements).
  • etc...

This is a problem with data duplication.

I 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 works:

   $("#editPopUp #submitChanges").click(function(event)
   {
    addNewRecord();
   });

addNewRecord() , , . , . , , . .

+3
3

:

// unbind event handler for button
$("#editPopUp #submitChanges").unbind("click", bindEditButtonEventListener);

, , :

$("#editPopUp #submitChanges").click(function(event)
{
 addNewRecord();
});

( , , ), , event, , :

$("#editPopUp #submitChanges").click(addNewRecord);

, .unbind(), :

$("#editPopUp #submitChanges").unbind("click", addNewRecord);

, "?"... , . , #addRecord, #editPopUp #submitChanges, , , .

+4

, unbind. "bindEditButtonEventListender".

:

$("#editPopUp #submitChanges").unbind("click");
+2

The bindEditButtonEventListener event is canceled, but you never bind it when you bind an anonymous method to the #submitChanges click event.

+2
source

Source: https://habr.com/ru/post/1755630/


All Articles