Search code examples
javascripthtmlvue.jseventsmdc-components

For the Menu Component of Material Design Web Components, how do I capture the "MDCMenu:selected" event in JavaScript?


I am using the Material Design Web Components component called "Menu."

After launching the menu, I need to be able to accessibly handle all the ways a "menu item" could be "selected." Adding an on-click via my framework's templating language (vue) works, however, adding methods for on-enter and other keys does not work. Example:

  <li
    v-for="option in options"
    :key="option"
    class="mdc-list-item"
    @click="onChange(option)" // this works
    @keyup.enter="onChange(option)" //this doesn't work
    role="menuitem">

I expect this is because the enter key has event handlers for closing the menu, which are catching my keypresses. I'm not entirely sure.

In any case, it seems the "proper" way to handle selections is via the MDCMenu:selected event. The description from the docs:

[MDCMenu:selected is] Used to indicate when an element has been selected. This event also includes the item selected and the list index of that item.

However, there are no instructions on how to capture this event. I've tried:

this.menu = new MDCMenu(this.$refs.menu);
this.menu.root.addEventListener(
  'MDCSimpleMenu:selected', ()=>{console.log('HELLOOOOOO')});

Which caused lots of undefined errors, which is weird because I can access this.menu.root and it appears to be a DOM element.

I've also tried:

this.menu = new MDCMenu(this.$refs.menu);
this.menu.addEventListener(
  'MDCSimpleMenu:selected', ()=>{console.log('HELLOOOOOO')});

Which threw an error about how addEventListener is not a function existing on this.menu;

I've searched through the source code but didn't find anything obvious about event handling or emitting.

How can I capture the MDCMenu:selected event?


Solution

  • The function is apparently called listen, and takes in the full string event name as the first argument, and the function to be invoked as the second argument.

     this.menu.listen('MDCMenu:selected',()=>{
       console.log('hi');
     });
    

    This is not documented anywhere I could find, I guessed it. If anybody can find the documentation I will accept that answer instead.