Search code examples
javascriptjqueryonclickjquery-nestable

Provide onclick dynamically and avoid duplicate event calling


I try to add an item, just like this sample: https://codepen.io/Gobi_Ilai/pen/LLQdqJ

var addToMenu = function () {
  var newName = $("#addInputName").val();
  var newSlug = $("#addInputSlug").val();
  var newId = 'new-' + newIdCount;

  nestableList.append(
    '<li class="dd-item" ' +
    'data-id="' + newId + '" ' +
    'data-name="' + newName + '" ' +
    'data-slug="' + newSlug + '" ' +
    'data-new="1" ' +
    'data-deleted="0">' +
    '<div class="dd-handle">' + newName + '</div> ' +
    '<span class="button-delete btn btn-danger btn-xs pull-right" ' +
    'data-owner-id="' + newId + '"> ' +
    '<i class="fa fa-times" aria-hidden="true"></i> ' +
    '</span>' +
    '<span class="button-edit btn btn-success btn-xs pull-right" ' +
    'data-owner-id="' + newId + '">' +
    '<i class="fa fa-pencil" aria-hidden="true"></i>' +
    '</span>' +
    '</li>'
  );

  newIdCount++;

  // update JSON
  updateOutput($('#nestable').data('output', $('#json-output')));

  // set events
  $("#nestable .button-delete").on("click", deleteFromMenu);
  $("#nestable .button-edit").on("click", prepareEdit);
};


 var deleteFromMenu = function () {
            var targetId = $(this).data('owner-id');
            var target = $('[data-id="' + targetId + '"]');
            var textConfirm = "Are you sure to delete" + target.data('name') + " ?";

                var result = confirm(textConfirm);
                if (!result) {
                    return;
                }

            // Remove children (if any)
            target.find("li").each(function () {
                deleteFromMenuHelper($(this));
            });

            // Remove parent
            deleteFromMenuHelper(target);

            // update JSON
            updateOutput($('#nestable').data('output', $('#json-output')));

        };

And after that try to delete one of the records. The page asked to confirm the question (1+added record) times. For example, if try to add 2 records, and try to delete one item(not last added item), 3 confirm message appears.

How could I manage $("#nestable .button-delete").on("click", deleteFromMenu); to see only one confirm question. Thanks.


Solution

  • Use .off(). The .off() method removes event handlers that were attached with .on().

    So in your case:

     $("#nestable .button-delete").off().on("click", deleteFromMenu);