1.1.1 • Published 2 years ago
@nsev/broadcast-channel v1.1.1
@nsev/broadcast-channel
About
A Wrapper around BroadcastChannel that uses @3xpo/events for node-style events in the browser.
Installation
pnpm i @nsev/broadcast-channelUsage
Basics
Tab 1
import { BroadcastChannel } from '@nsev/broadcast-channel';
const channel = new BroadcastChannel('foobar');
channel.send('I am not alone');Tab 2
import { BroadcastChannel } from '@nsev/broadcast-channel';
const channel = new BroadcastChannel('foobar');
channel.on('message', (message) => {
  console.log(message); // I am not alone
});Typesafety
Just like in the original, just pass the type as a generic.
import { BroadcastChannel } from '@nsev/broadcast-channel';
type Message = {
  foo: 'bar';
  bar: 'hi';
} | {
  foo: 'baz';
  baz: string;
};
const channel = new BroadcastChannel<Message>('foobar');
channel.on('message',e=>{
  // e is of type Message
})
// ok
channel.send({
  foo: 'bar',
  bar: 'hi',
});
// ok
channel.send({
  foo: 'baz',
  baz: 'hi',
});
// ok
channel.send({
  foo: 'baz',
  baz: 'hello there',
});
// not ok
channel.send({
  foo: 'bar',
  baz: 'hi',
});
// not ok
channel.send({
  foo: 'baz',
  bar: 'hi',
});
// not ok
channel.send({
  foo: 'bar',
  bar: 'hi',
  baz: 'hello there',
});