0

I try to remove an event listener with Javascript, but it seems not working.

I need to pass the object event in the handler so this is why I'm using .bind().

My code :

if (sidebar) {
  listItems.forEach(function(listItem) {
    listItem.showSubmenu = showSubmenu;
    listItem.addEventListener('click', listItem.showSubmenu.bind(this, subLists), true);
  });

  if (sidebarButton) {
    sidebarButton.addEventListener('click', onClickOnButton.bind(this, sidebar));
  }
}

if (sidebar.getAttribute('data-reduce') === 'true') {
  listItems.forEach(function(listItem) {
    listItem.removeEventListener('click', listItem.showSubmenu, true);
  });
}

function showSubmenu(subLists, e) {
  var target = e.currentTarget,
      subList = target.querySelector('.sidebar__sublist');

  if (subList) {

    if (subList.style.display !== 'block') {

      [...subLists].forEach(hideSubList);

      $(subList).slideDown('slow', function() {
        subList.style.display = 'block';
        target.querySelector('.sidebar__list__item__link__arrow').textContent = 'keyboard_arrow_up';
      });

    } else {
      $(subList).slideUp('slow', function() {
        subList.style.display = 'none';
        target.querySelector('.sidebar__list__item__link__arrow').textContent = 'keyboard_arrow_down';
      });
    }
  }
}

Result : The event is not removed.

5
  • 3
    listItem.showSubmenu is not the same as listItem.showSubmenu.bind(this, subLists). When you bind a new object is created to handle. Commented Dec 4, 2020 at 13:49
  • Needing to remove an event listener is a code smell in my book Commented Dec 4, 2020 at 13:51
  • @GACy20 Yes but I need to passe the object event, so is there any other solution ? Commented Dec 4, 2020 at 13:57
  • @tonymx227 you already have jQuery. why not use .on() and .off() ? Commented Dec 4, 2020 at 14:07
  • I'm in process to remove my jQuery library, in the next few months I want to use native javascript. Commented Dec 4, 2020 at 14:08

1 Answer 1

1

as @GACy20 said listItem.showSubmenu is not the same as listItem.showSubmenu.bind(this, subLists)

try doing it like this

listItem.showSubmenu = showSubmenu.bind(this, subLists);
listItem.addEventListener('click', listItem.showSubmenu, true);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.