@atomico/channel
v0.0.1
Published
sharing states between WebComponents or DOM easily.
Downloads
1,570
Readme
@atomico/channel
@atomico/channel
allows sharing states between WebComponents or DOM easily.
This API is inspired by the objectives of React Context, but eliminates the complexity and is an agnostic implementation.
What is a channel?
A channel is a sender and a receiver of status through the native event system of the DOM, a channel has the following logic:
- read the context of parent
- modify the context for children
Example
This is an example where the webcomponent subscribes to the parent node:
import { Channel } from "@atomico/channel";
const CHANNEL = "MyChannel";
// Parent channel
const parentChannel = new Channel(document.body, CHANNEL);
class MyComponent extends HTMLElement {
constructor() {
super();
// Child channel
this.channel = new Channel(this, CHANNEL);
}
connectedcallback() {
this.channel.connected(
(data) => (this.textContent = JSON.stringify(data))
);
}
disconnectedCallback() {
this.channel.disconnect();
}
}
// Connect the channel to the native DOM event system
parentChannel.connect();
parentChannel.cast("I'm your father");
API
Channel()
const channel = new Channel(
// Element
host,
// string
"idString",
// associates the composed option to the event
// this allows bypassing the shadowDOM when connecting the channels
true
);
channel.connect()
channel.connect(optionalCallback);
Where:
optionalCallback
: optional callback that allows to read the transmissions of the parent.
channel.disconect()
Remove subscriptions
channel.cast()
Issues a new broadcast to the child channels
channel.cast(10);
channel.cast({ data });
Executing this method prevents any transmission from the parent from spreading to the children of this channel.