-
Notifications
You must be signed in to change notification settings - Fork 0
How do you recommend getting data from a custom element
You can either
- Send data from a custom event
- Create a public function to return data.
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('todo-submit', (e)=> {
console.log(e.detail)
todoService.addTodo(e.detail)
})
The idea here is to have a function you can call to get data, but this would still require some way of knowing when to collect the data, which requires a custom event. This would work for a use case when you just want to be able to collect the data when you want to.
submitTodoItem() {
this.dispatchEvent(new CustomEvent('todo-submit'))
}
getTodoData() {
return {
todoValue: this.todoInput.value,
someOtherValue: value
}
}
So outside of the custom element we can call the function
let todoList = document.querySelector('todo-list')
const data = todoList.getTodoData()
or
todoList.addEventListener('todo-submit', ()=> {
todoService.addTodo(todoList.getTodoData())
})
To manage data or business logic, use a service