Custom events and delegate

I’ve been creating a component using Material web components as a basis. Only thing I’m stuck on is how to watch for a custom event being fired, or rather the naming of it.

let changeEvent;
   if (window.CustomEvent) {
            changeEvent = new CustomEvent('MDCTabBar:activated', {
              detail: {
                index
              },
              bubbles: true
            });
          } else {
            changeEvent = document.createEvent('CustomEvent');
            changeEvent.initCustomEvent('MDCTabBar:activated', true, true, {
              detail: {
                index
              }
            });
          }
          this.root_.dispatchEvent(changeEvent);

I tried using it liked so:

<tab-bar MDCTabBar:activated.delegate="doSomething()"></tab-bar>

but it doesn’t seem to catch it. If I change the event name to ‘foo’ and use

<tab-bar foo.delegate="doSomething()"></tab-bar> it does.

Is there a guide on how to use custom event names with delegate?

Thanks in advance.

Html template is case insensitive, so your MDCTabBar:activated.delegate="doSomething()" will actually be seen as mdctabbar:activated.delegate="doSomething()". To work around this, you could change all event names to lowercase only, or listen to the event in the view model:

  <tab-bar ref='tabBarEl'></tab-bar>
class MyEl {
  tabBarEl: Element;

  onTabBarActivated = ($event) => {}

  bind() {
    this.tabBarEl.addEventListener('MDCTabBar:activated', this.onTabBarActivated);
  }

  unbind() {
    this.tabBarEl.removeEventListener('MDCTabBar:activated', this.onTabBarActivated);
  }
}
2 Likes

Ok thanks for that. I’ll give both options a go.

Paul.

Hi, I know it’s old thread but still relevant…

Other bindings work by converting foo-bar.bind to fooBar.

Can similar behavior be achieved for trigger and delegate binding?