Custom events and delegate


#1

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.


#2

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);
  }
}

#3

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

Paul.