Skip to content

Instantly share code, notes, and snippets.

@vdegenne
Created February 3, 2023 09:56
Show Gist options
  • Save vdegenne/f382358e67a5e864b4d21c78b4745ded to your computer and use it in GitHub Desktop.
Save vdegenne/f382358e67a5e864b4d21c78b4745ded to your computer and use it in GitHub Desktop.

Defining a channel

channel.js

import { Channel } from 'channel-library'

export const channel = new Channel()

Consuming

my-element.js

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

class MyElement extends LitElement {
  constructor () { super()
    // basic subscribe
    channel.subscribe(this)
    
    // when the channel receives an event
    channel.on('update', () => this.requestUpdate())
    channel.on('update:important', () => this.requestUpdate())
  }
  
  render() { return html`
    <button @click=${() => {
      // send event to all subscribed channels
      channel.broadcast('update')
    }}>broadcast</button>
    `
  }
}

my-element2.js

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

export MyElement2 extends LitElement {
  constructor() { super()
    channel.subscribe(this)
    
    channel.on('update', () => this.requestUpdate())
  }
  
  render() { return html`
    <!-- update only important -->
    <button @click=${() => { channel.broadcast('update:important') }}>update important</button>
    `
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment