šŸ‡¬šŸ‡§ LitElement - First steps - Part IV - Components communication

Previously (read it before šŸ™)

Yesterday, I wrote a post on how we can make the components communicate (Talk to components). A moment after @WestbrookJ send me a message on Twitter https://twitter.com/WestbrookJ/status/1084290962619277312 saying:

"I often rely on document as a master event listener so I can dispatch a bubbling event anywhere and get it heard"

And, he's right. His solution is clever and simpler.

Update the starting component

So let me, first to update the source code of main-application.js by changing the constructor:

constructor() {
  super()
  this.addEventListener('add-buddy', this.onMessage)
}

I added a listener to the component with the highest level in my web application (the "starting component"). Now, main-application is listening for the add-buddy event.

I will add an onMessage method to the component, but before, let's update the source code of the button component.

Update the button component

I updated the clickHandler() method of my-amazing-button.js like that

clickHandler() {
  this.counter+=1

  this.dispatchEvent(
    new CustomEvent('add-buddy', {  
      bubbles: true, composed: true, detail: {
        value: `šŸ» Teddy nĀ°${this.counter}`
      } 
    })
  )
}

āš ļø Remark: don't forget to use bubbles and composed

From the Mozilla documentation:

  • bubbles: A Boolean indicating whether the event bubbles up through the DOM or not.
  • composed: A Boolean value indicating whether or not the event can bubble across the boundary between the shadow DOM and the regular DOM.

Now, each time I will click on the button, I will dispatch a custom event with this value: šŸ» Teddy nĀ°${this.counter}. And I want to add this to my buddies' list.

Update the list component

I removed the previous code of the constructor (see Talk to components) and added a new method addBuddy(buddy) to the list:

constructor() {
  super()
  this.buddies = [
    "šŸ¦Š Foxy",
    "šŸ¦ Leo",
    "šŸÆ Tigrou"
  ]
}

addBuddy(buddy) {
  this.buddies = [...this.buddies, buddy]
}

And now, I just have to add the appropriate method to main-application to call the addBuddy(buddy) method when the add-buddy event is triggered.

Update the starting component

Then, one last time, I will update main-application.js by adding an onMessage method:

onMessage(message) {
  if(message.type==='add-buddy') {
    this.shadowRoot.querySelector('buddies-list').addBuddy(message.detail.value)
  }    
}

And, now you can test again:

html

That's all. Have a nice Sunday šŸ˜ƒ

If you need all the files of the project, it's here https://gitlab.com/bots-garden/training-materials/bootstrapping-a-litelement-project/tree/03-dispatch-events.

Last Articles

Last Updated: 1/13/2019, 2:49:02 PM