2

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);
     }
Jose Raul Perera
  • 778
  • 1
  • 7
  • 35

2 Answers2

2

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 });
mishu
  • 5,347
  • 1
  • 21
  • 39
  • 1
    @JoseRaulPerera you are welcome, I am glad it helps. Also you can note that you need to provide the flags `bubbles` and `composed` for the event to "escape" the shadow DOM boundaries, but in this way that you're listening for it you are actually getting an event that happens *inside* `my-item`, so your code should work even without them, just with the *detail* provided. Since you're not stopping the propagation in `my-view` it might be a good idea to have it stop there instead of bubbling it up to the top level (that is if you don't need it above, ofc) – mishu May 02 '18 at 13:52
  • thanks, I will remove this so we don't have performance issues or memory leaks in the app. Thanks so much – Jose Raul Perera May 02 '18 at 13:53
0

On your HTML do something like:

<div id="foo" style="width:20px;height:20px;background-color:#ffcc00;" onclick="javascript:updateFired(event)"></div>

And in your javascript:

const el = document.getElementById('foo');
el.onclick = showFoo;


function showFoo() {
  alert('Clicked!');
}
Tiago Machado
  • 170
  • 3
  • 11