Manage event subscriptions with Turkey
Turkey provides a subscription API that allows users to subscribe to events and returns a mechanism to unsubscribe from those events.
website·Indexed 29 days ago
https://toukey.vercel.app/A simple tool featuring a subscription API that allows users to unsubscribe from events.
subscribe function to listen for a specific key. The subscribe function returns an unsubscribe function that can be called to remove the event listener.import { subscribe } from "toukey";
// Subscribe to a key
const unsubscribe = subscribe("scope", () => {
console.log("scope");
});
// Cancel the listener
unsubscribe();+ symbol.import { subscribe } from "toukey";
// Trigger if either 'scope' or 'a' is pressed
subscribe("scope, a", () => {
console.log("scope or a");
});
// Trigger on key combination (e.g., Ctrl+A)
subscribe("ctrl+a", () => {
console.log("ctrl+a");
});npm install toukey -SThe third parameter of subscribe allows you to specify the scope of the event. The default scope is "default". You can pass a string or a configuration object { scope: "name" }.
If the scope is set to "*", the listener will trigger regardless of the current active scope setting.
import { subscribe, setScope } from "toukey";
// Standard scope
subscribe("scope", () => console.log("default"), "default");
subscribe("scope", () => console.log("sub"), { scope: "sub" });
// Global scope (ignores current scope setting)
subscribe("scope", () => console.log("always triggers"), "*");
// Change the active scope
setScope("sub");toukey.subscribe method is used to listen for specific key presses.<script src="https://unpkg.com/toukey/dist/toukey.umd.min.js"></script>
<script>
toukey.subscribe('space', function() {
console.log('space');
});
</script>subscribe within a useEffect hook. Since subscribe returns an unsubscribe function, you can return it directly from the useEffect cleanup function to prevent memory leaks.import { useEffect } from "react";
import { subscribe } from "toukey";
function App() {
useEffect(() => {
return subscribe("scope", () => {
console.log("scope");
});
}, []);
return <div>hello world</div>;
}