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>**