Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
How to handle and pass events to the lit component from defining component

I am trying to design web components using lit Element and I need an help regarding the events. As we can see from the attached snippet we could use @change="${this.handleEvent}" in html template and handle the function handleEvent(e){} inside the lit Element component. By this the events are limited and controlled only in the lit web components.

However, when other people use our web components they don't have much control or access to the values over these events in the defining component. For instance, if we have an index.html file and I use it like <my-element onchange="handleEvent(e)"></my-element>, I should have the access to the onchange event and call a function inside the index file only.

So, Is there a way to achieve this to the similar behavior of regular html events instead of writing the events which is limited in the lit Element web components.

<script src="https://unpkg.com/@webcomponents/webcomponentsjs@latest/webcomponents-loader.js"></script>
<script type="module">
  import { LitElement, html, css } from 'https://unpkg.com/lit-element/lit-element.js?module';
  
  class MyElement extends LitElement {
  
   static get properties() {
      return {
        checked:  { type: Boolean, attribute: true }
      };
    }
    
    static get styles() {
      return [
        css`
          div {
            padding: 10px;
            width: 90px;
            border: 2px solid orange;
          }
        `
      ];
    }
    
    render() {
      return html`
      <div>
         <input
            @change="${this.handleEvent}"
            ?checked="${this.checked}"
            type="checkbox" /> Checkbox
       </div>
      `;
    }
    
    handleEvent(e) {
      console.log(`Checkbox marked as: ${e.target.checked}`);
    }
  }
  customElements.define('my-element', MyElement);
</script>

// Index.html
<my-element></my-element> 
// I am expecting to pass an event and handle it in the importing 
component. 
// Something like: **<my-element onchange="handleEvent(e)"}></my- 
element>**

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

If you want to listen to events outside your element, you should dispatch an event like this:

const event = new Event('my-event', {bubbles: true, composed: true});
myElement.dispatchEvent(event);

The Lit documentation on events gives a good overview of how and when to dispatch events https://lit.dev/docs/components/events/#dispatching-events

about 4 years ago · Juan Pablo Isaza Denunciar

0

Usually with your own custom elements you'll probably also want to define your own API to offer that to consumers of your components. That often also comes with defining your own events which your component emits.

See this simple (non-lit, but you get the idea) example:

customElements.define('foo-bar', class extends HTMLElement {
  input = document.createElement('input');
  constructor() {
    super();
    this.input.type = 'checkbox';
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.appendChild(this.input);
    this.input.addEventListener('change', this.handleChange.bind(this));
  }
  // replaces the internal change event with an event you publish to the outside world
  // this event is part of your defined API.
  handleChange(e) {
    e.stopPropagation();
    const stateChange = new CustomEvent('state-change', { 
      bubbles: true, 
      composed: true,
      detail: { checked: this.input.checked }
    });
    this.dispatchEvent(stateChange);
  }
});

document.addEventListener('state-change', (e) => { console.log(e.detail); })
<foo-bar></foo-bar>

If you also want to support declarative event binding as the standard HTML elements do (and using which is widely considered bad practice), you can achieve that using observed attributes:

customElements.define('foo-bar', class extends HTMLElement {
  input = document.createElement('input');
  constructor() {
    super();
    this.input.type = 'checkbox';
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.appendChild(this.input);
    this.input.addEventListener('change', this.handleChange.bind(this));
    this.declarativeValueChangeListener = this.declarativeValueChangeListener.bind(this);
  }
  // replaces the internal change event with an event you publish to the outside world
  // this event is part of your defined API.
  handleChange(e) {
    e.stopPropagation();
    const stateChange = new CustomEvent('state-change', { 
      bubbles: true, 
      composed: true,
      detail: { value: this.input.value }
    });
    this.dispatchEvent(stateChange);
  }
  
  static get observedAttributes() { 
    return [ 'onstatechange' ];
  }
  
  attributeChangedCallback(attr, oldVal, newVal) {
    if (oldVal === newVal) return; // nothing changed, nothing to do here
    if (newVal === null) { // attribute was removed
      this.removeEventListener('state-change', this.declarativeValueChangeListener)
    } else { // attribute was added
      this.addEventListener('state-change', this.declarativeValueChangeListener)
    }
  }
  
  declarativeValueChangeListener() {
    const functionStr = this.getAttribute(this.constructor.observedAttributes[0]);
    eval(functionStr);
  }
});


function baz() { console.log('baz executed through declarative binding of an outside handler!'); }
<foo-bar onstatechange="baz()"></foo-bar>

about 4 years ago · Juan Pablo Isaza Denunciar

0

I don't understand why you need Events,
when a click on the input can execute either global Functions or local Methods.

No need for oldskool bind mumbo-jumbo, no need for observedAttributes

You can use the default onchange, because all Events exist on HTMLElement
Only inputs like textarea actually fire the Change Event

Used on any other HTMLElement nothing happens, you have to call this.onchange() or document.querySelector("foo-bar").onchange() yourself.
You can not do that with your own attribute names, as those values will always be a String, and not parsed as JS code by the Browser engine.

You need eval(code) though to execute the code within Component scope and make onchange="this.baz()" work.

customElements.define('foo-bar', class extends HTMLElement {
  constructor() {
    let input = document.createElement("input");
    input.type = "checkbox";

    super()
      .attachShadow({mode: 'open'}) 
      .append(input,"click me to execute ", this.getAttribute("onchange"));

    this.onclick = (evt) => { // maybe you only want input.onclick
      //evt.stopPropagation();
      let code = this.getAttribute("onchange");
      try {
        eval(code); // this.onchange() will only execute global functions
      } catch (e) {
        console.error(e,code);
      }
    }
  }
  baz() {
    console.log("Executed baz Method");
  }
});

function baz() {
  console.log("Executed baz Function");
}
<foo-bar onchange="baz()"></foo-bar>
<foo-bar onchange="this.baz()"></foo-bar>

<style>
 foo-bar { display:block; zoom:2 }
</style>

Important note

shadowDOM is what saves your ass here.

The onchange Event from the input does not escape shadowDOM
(Like composed:true does on Custom Events)

Without shadowDOM all onchange declarations on parent Elements will fire, because the Event bubbles:

<div onchange="console.log(666)">
  <input onchange="console.log(this)" type="checkbox">
</div>

<style>
  input { zoom:3 }
</style>

This is a good example where a shadowRoot on a regular HTMLElement can have value, without declaring a Custom Element

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda