How to add extra eventlistener to menu object in attached library This is my first Drupal 8 project and I'm running into a problem figuring out how to attach an extra event handler to an object.
I am working on a custom theme using Radix as base theme. I am using Superfish as menu module.
One of the issues is that Superfish creates an extra 'root' menu called 'Menu' that is shown when the Bootstrap hamburger menu is clicked. You subsequently need to click on 'Menu' to show the actual (accordion) menu.
I found a snippet of code in an issue: https://www.drupal.org/project/superfish/issues/2891228 that hides the 'Menu' toggle, but I cannot get it to work.

I have setup a library definition and created a 'script.js':

import "popper.js";
import "bootstrap";

(function($, Drupal) {
  Drupal.behaviors.helloWorld = {
    attach(context) {
      console.log("Hello World");
    }
  };


  Drupal.behaviors.myMainMenu = {
    attach(context) {
      console.log("myMainMenu: " + context.toString());
      $(".navbar-collapse", context).once('myMainMenu').on(
        "show shown shown.bs.collapse show.bs.collapse",
        () =&gt; {
        console.log("navbar-collapse");
        if (!$("#superfish-main-accordion").hasClass("sf-expanded")) {
          console.log('no expand');
          $(".superfish-main-toggle")
            .click()
            .hide();
        }
      });
    }
  };
})(jQuery, Drupal);



I know the script runs, because I see 'Hello World' and 'myMainMenu' + some glob several times in the console. But I never manage to get the other console messages.

I also know the code in the if statement is correct, because, if I run it manually in the console, it works as intended.

What should be the correct code?
Couple of problems. But the main two are:


In Drupal 8, you need to call $.each() on $.once()
In Drupal you don't need to call $.on() on elements. The combination of Drupal.behaviors and $.once() achieves the same goal.


So your code should be something like:

$(".navbar-collapse", context).once('myMainMenu').each(function () {
  // Do stuff here
});