🇬🇧 LitElement - First steps - Part III

updated on 2019-01-13 with LitElement 2.0.0-rc.2

Previously (read it before 🙏)

⚠️ This blog post is about "experimental" stuff. It's a quick post, but, IMHO a useful post (at least I hope so).

Today, my goal is to find a way to make possible communication between LitElements (I mean: how a component A can send a message to a component B)

If you have better or other ideas to reach the same result, I will be happy to read you, so ping me on Twitter (@k33g_org) or comment on this post. Enjoy the reading.

How to talk to a component (a LitElement component)?

I needed a simple method, and finally, I decided to use the JavaScript CustomEvents to implement quickly, a kind of "observable" components. For example, today, I would like to be able to send "messages" to my buddies-list to add a buddy to this list from anywhere (from my web application)

So, first, I need to register my components (at least those with whom I want to communicate) somewhere to be able to "reach" them easily.

For that, I will use the global window object 🙀 (we can change that later). Then turn the source code of the constructor of the buddies-list like that:

constructor() {
  super()
  this.buddies = [
    "🦊 Foxy",
    "🦁 Leo",
    "🐯 Tigrou"
  ]

  if(window.components == null) window.components = []
  window.components.push(this)

  this.addEventListener("new buddy", e => {
    this.buddies = [...this.buddies, e.detail]
  })
  
}

👋 Remark: I use this this.buddies = [...this.buddies, e.detail] instead of this.buddies.push(e.detail) to override the complete array instead of mutating it, otherwise the refreshwill not be triggered.

Now, reload the web application and open the webtools console and type this command:

let newBuddyEvent = new CustomEvent("new buddy", {detail: "🐼 Pandy" })
window.components.forEach(component => component.dispatchEvent(newBuddyEvent))

So, what have I done? I created a JavaScript CustomEvent: new CustomEvent("new buddy", {detail: "🐼 Pandy" }) (cf. https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent), then I tried to dispatch it to all components og my application (component.dispatchEvent(newBuddyEvent))

And the result is:

html

We have a 🐼 in the buddies list ğŸŽ‰

If you don't want to use the global window object, you can create a new JavaScript file components.js with this source code:

export const components = []

and now, you can use it like that with your components:

import { components } from './components.js'

//window.components.push(this)
components.push(this)

That's all for today. Have a great week-end 😃

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

Last Articles

Last Updated: 1/13/2019, 6:46:18 AM