Skip to content

How do you handle user events from the custom element

Gabriel Forti edited this page Jul 31, 2018 · 8 revisions

This ties in with

How do you recommend getting data from a custom element

So the idea is you might have a custom element where the user has to click on a button to submit some data entered in a text field.

<label>Todo:</label> <input name="todo" /> <button>Add</button>

For the <button> tag we can use the click event inside the custom element.

this.todoInput = this.shadowRoot.querySelector('input[name="todo"]');
this.btnSubmit = this.shadowRoot.querySelector('button');      

When the custom element is connected we attach an event listener

connectedCallback() {
    this.btnSubmit.addEventListener('click', this.submitTodoItem.bind(this))
}

What we then what to do is be able to send out a custom event to inform the developer that the button was clicked

submitTodoItem() {
    this.dispatchEvent(new CustomEvent('todo-submit', { detail: this.todoInput.value }))
}

Notice how we can also send the data in the detail object

More info: MDN - Creating and triggering events

So outside of the custom element we can listen to the events

let todoList = document.querySelector('todo-list')
todoList.addEventListener('add-submit', (e)=> {
    console.log(e.detail)
    todoService.addTodo(e.detail)
})
Clone this wiki locally