-
Notifications
You must be signed in to change notification settings - Fork 0
How do you handle user events from the custom element
Gabriel Forti edited this page Jul 31, 2018
·
8 revisions
This ties in with
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: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
So outside of the custom element we can listen to the events
let todo = document.querySelector('todo-list')
todo.addEventListener('add-submit', (e)=> {
console.log(e.detail)
todoService.addTodo(e.detail)
})