Search code examples
javascriptpolymerweb-componentdom-repeat

Fire a CustomEvent from element in dom-repeat


Hello I have this issue with a dom-repeat template. I have an element with a dom-repeat and inside I'm showing a my-item element, I have a button that fired a custom event and I need to get that event in the parent element but I can't make it work. Any thoughts on this? Why I never get updateFired(e) called?

Element: my-view

<template is="dom-repeat" items="{{employees}}">
      <my-item employee="[[item]]" on-update="updateFired"></my-item>
    </template>
    updateFired(e) {
      console.log(e);
    }

Element: my-item

<div class="container">
        <div>First name: <span>[[employee.first]]</span></div>
        <div>Last name: <span>[[employee.last]]</span></div>
        <button on-click="testClick">Click</button>
    </div>
    testClick(e) {
        const event = new CustomEvent('onUpdate', { bubbles: true, composed: true, detail: this.employee });
        this.dispatchEvent(event);
     }

Solution

  • In the way you wrote the event handler your event name should be "update", not "onUpdate". The on- prefix is added just for defining the event handler, the actual event name should be the part after it.

    So you would need to change

    const event = new CustomEvent('onUpdate', { bubbles: true, composed: true, detail: this.employee });
    

    to

    const event = new CustomEvent('update', { bubbles: true, composed: true, detail: this.employee });