Skip to content

How do you recommend getting data from a custom element

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

You can either

  1. Send data from a custom event
  2. Create a public function to return data.

Custom Event

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)
})

Public Function

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

Clone this wiki locally