wirec
v1.3.0
Published
A plain JavaScript event broker designed for facilitating cross-component data exchange.
Downloads
94
Maintainers
Readme
wirec
A plain JavaScript event broker designed for facilitating cross-component data exchange, such as updating one component's (React, Vue etc) state from another. It's versatile and can be utilized anywhere in your codebase.
Installation
yarn add wirec
OR
npm i wirec
Import
import wirec from "wirec";
OR
const wirec = require("wirec");
Methods
| Method | Args | Return | Desc | |------------|---------------|-----------------|---------| | wirec.on | event_key: string callback: function | { callback_id: string, unlink: function} | Add an event listner | | wirec.onx | callback_id: string | void | Remove event listener | | wirec.ons | event_key: string callback: function | { callback_id: string, unlink: function} | Set an event listener that removes all other event listeners for the same event and sets the current one. | | wirec.put | event_key: string ...args: any | void | Dispatch an event | | wirec.hook | event_key: string | (...args) => void | Directly hooking listener to a DOM event |
Examples
// Fruits.jsx
import wirec from "wirec";
import { useState, useEffect } from "react";
export default function Fruits() {
const [fruits, setFruits] = useState(["Apple", "Banana"]);
useEffect(() => {
const { unlink } = wirec.on("fruits", (items) => {
setFruits([...items]);
});
return unlink;
},[]);
return (
<ul>
{fruits.map((fruit) => (
<li key={fruit}>{fruit}</li>
))}
</ul>
)
}
// Another.jsx
import wirec from "wirec";
export default function Another() {
const sendFruits = () => {
wirec.put("fruits", ["Orange", "Strawberry"]);
}
return (
<div>
<button onClick={sendFruits}>Send</button>
</div>
)
}
Directly hooking listener to a DOM event
wirec.on("signup", (e) => {
// ...
});
<form onSubmit={wirec.hook("signup")}>
...
</form>
Directly accessing a state
// Component1.jsx
import { useState } from "react";
import wirec from "wirec";
export default function Component1() {
const [count, setCount] = wirec.state.init("count", useState, 0);
return (
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
)
}
// Component2.jsx
import wirec from "wirec";
export default function Component2() {
const count = wirec.state.get("count");
return (
<div>
Another:
<button onClick={() => wirec.state.set("count", count + 1)}>Count++</button>
<button onClick={() => wirec.state.set("count", Math.random())}>Random</button>
</div>
)
}