{"id":19210788,"url":"https://github.com/flekschas/pub-sub","last_synced_at":"2025-07-18T20:36:59.734Z","repository":{"id":32946403,"uuid":"147245901","full_name":"flekschas/pub-sub","owner":"flekschas","description":"A tiny 0.8 KB pub-sub event library that supports cross-window messaging and async event broadcasting","archived":false,"fork":false,"pushed_at":"2024-11-06T20:55:02.000Z","size":745,"stargazers_count":12,"open_issues_count":4,"forks_count":3,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-06-15T04:16:22.731Z","etag":null,"topics":["broadcasting","event-handling","event-management","javascript","pubsub","typescript"],"latest_commit_sha":null,"homepage":"http://pub-sub.lekschas.de/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/flekschas.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2018-09-03T19:36:00.000Z","updated_at":"2024-11-06T20:55:04.000Z","dependencies_parsed_at":"2024-03-25T01:27:00.800Z","dependency_job_id":"fa960dee-f8c9-4513-bc27-c43b89e3cc0a","html_url":"https://github.com/flekschas/pub-sub","commit_stats":null,"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"purl":"pkg:github/flekschas/pub-sub","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flekschas%2Fpub-sub","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flekschas%2Fpub-sub/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flekschas%2Fpub-sub/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flekschas%2Fpub-sub/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/flekschas","download_url":"https://codeload.github.com/flekschas/pub-sub/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flekschas%2Fpub-sub/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265829207,"owners_count":23835090,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["broadcasting","event-handling","event-management","javascript","pubsub","typescript"],"created_at":"2024-11-09T13:38:00.745Z","updated_at":"2025-07-18T20:36:59.710Z","avatar_url":"https://github.com/flekschas.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PubSubES: A tiny ES6-based pub-sub library\n\n[![npm version](https://img.shields.io/npm/v/pub-sub-es.svg)](https://www.npmjs.com/package/pub-sub-es)\n[![stability experimental](https://img.shields.io/badge/stability-stable-green.svg)](https://nodejs.org/api/documentation.html#documentation_stability_index)\n[![build status](https://img.shields.io/github/actions/workflow/status/flekschas/pub-sub/build.yml?branch=master\u0026color=a17fff)](https://github.com/flekschas/pub-sub/actions?query=workflow%3Abuild)\n[![gzipped size](https://img.shields.io/bundlephobia/minzip/pub-sub-es?color=6ae3c7\u0026label=gzipped%20size)](https://unpkg.com/pub-sub-es)\n[![code style prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)\n[![demo](https://img.shields.io/badge/demo-online-c15de2.svg)](http://pub-sub.lekschas.de)\n\n\u003e A [tiny \u003c1KB](https://bundlephobia.com/result?p=pub-sub-es) [pub-sub](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)-based event library that lets you send custom message within and cross the window! It's written in ES6 and makes use of the awesome [Broadcast Channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API).\n\n**Demo:** [pub-sub.lekschas.de](http://pub-sub.lekschas.de)\n\n## Install\n\n```\nnpm -i -D pub-sub-es\n```\n\n## Get Started\n\n```javascript\nimport createPubSub from 'pub-sub-es';\n\n// Creates a new pub-sub event listener stack.\nconst pubSub = createPubSub();\n\n// Subscribe to an event\nconst myEmojiEventHandler = (msg) =\u003e console.log(`🎉 ${msg} 😍`);\npubSub.subscribe('my-emoji-event', myEmojiEventHandler);\n\n// Publish an event\npubSub.publish('my-emoji-event', 'Yuuhuu'); // \u003e\u003e 🎉 Yuuhuu 😍\n\n// Unsubscribe\npubSub.unsubscribe('my-emoji-event', myEmojiEventHandler);\n```\n\n### Type Events\n\nBy default, `pub-sub` assumes you are publishing any kind of events with an\nunknown payload. With TypeScript you can specify which events (name and payload)\nyou are publishing as follows.\n\n```typescript\nimport createPubSub, { Event } from 'pub-sub-es';\n\ntype Events = Event\u003c'init' | 'destroy', undefined\u003e \u0026\n  Event\u003c'solution', number\u003e \u0026\n  Event\u003c'selection', number[]\u003e;\n\nconst pubSub = createPubSub\u003cEvents\u003e();\n```\n\nWith this, we established that `pubSub` will handle four events:\n\n- `init` and `destroy` feature no payload (i.e., the payload is `undefined`)\n- `solution` features a single `number` as payload\n- `selection` features an array of numbers as payload\n\nWhen you listen to or publish an event, the payload will now be typed based of the event. I.e.:\n\n```typescript\npubSub.subscribe('destroy', (payload) =\u003e payload === undefined); // =\u003e ✅\npubSub.subscribe('destroy', (payload) =\u003e payload * 2); // =\u003e ❌\npubSub.subscribe('solution', (payload) =\u003e console.log(payload + 2)); // =\u003e ✅\npubSub.subscribe('solution', (payload) =\u003e console.log(payload.length)); // =\u003e ❌\npubSub.subscribe('selection', (payload) =\u003e console.log(payload.length)); // =\u003e ✅\npubSub.subscribe('selection', (payload) =\u003e console.log(payload * 2)); // =\u003e ❌\n\npubSub.publish('init'); // =\u003e ✅\npubSub.publish('init', 'w00t'); // =\u003e ❌\npubSub.publish('solution', 42); // =\u003e ✅\npubSub.publish('solution', '42'); // =\u003e ❌\npubSub.publish('selection', [1,3,3,7]); // =\u003e ✅\npubSub.publish('selection', 1337); // =\u003e ❌\n```\n\n## API\n\n`pub-sub-es` exports the factory function (`createPubSub`) for creating a new pub-sub service by default and a global pub-sub service (`globalPubSub`). The API is the same for both.\n\n#### `createPubSub(options = { async: false, caseInsensitive: false, stack: {})`\n\n\u003e Creates a new pub-sub instances\n\n**Arguments:**\n\n- `options` is an object for customizing pubSub. The following properties are understood:\n  - `async`: when `true`, events are published asynchronously to decouple the process of the originator and consumer.\n  - `caseInsensitive`: when `true`, event names are case insensitive\n  - `stack`: is an object holding the event listeners and defaults to a new stack when being omitted.\n\n**Returns:** a new pub-sub service\n\n#### `pubSub.publish(event, news, options = { async: false, isNoGlobalBroadcast: false})`\n\n\u003e Publishes or broadcasts an event with some news or payload\n\n**Arguments:**\n\n- `event` is the name of the event to be published.\n- `news` is an arbitrary value that is being broadcasted.\n- `options` is an object for customizing the behavior. The following properties are understood:\n  - `async`: overrides the global `async` flag for a single call.\n  - `isNoGlobalBroadcast`: overrides the global `isGlobal` flag for a single call.\n\n#### `pubSub.subscribe(event, handler, times)`\n\n\u003e Subscribes a handler to a specific event\n\n- `event` is the name of the event to be published.\n- `handler` is the handler function that is being called together with the broadcasted value.\n- `times` is the number of times the handler is invoked before it's automatically unsubscribed.\n\n**Returns:** an object of form `{ event, handler }`. This object can be used to automatically unsubscribe, e.g., `pubSub.unsubscribe(pubSub.subscribe('my-event', myHandler))`.\n\n#### `pubSub.unsubscribe(eventOrSubscription, handler?)`\n\n\u003e Unsubscribes a handler from listening to an event\n\n- `eventOrSubscription` is the name of the event to be published. Optionally, `unsubscribe` accepts an object of form `{ event, handler}` coming from `subscribe`.\n- `handler` is the event handler function to be unsubscribed from the event\n\n#### `pubSub.clear()`\n\n\u003e Removes all currently active event listeners and unsets the event times.\n\n_Note: this endpoint is not available on the global pub-sub because it could have undesired side effects. You need to unsubscribe global event listeners manually instead._\n\n### Between-context messaging\n\nThe global pub-sub instance is created when `pub-sub-es.js` is loaded and provides a way for\nglobal messaging within and between contexts. It utilizes the [Broadcast Channel API](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel). Note, when sending sending objects from one context to another you have to make sure that they are cloneable. For example, trying to broadcast a reference to a DOM element will fail.\n\n## Difference to other pub-sub libraries\n\nYou might have come across the awesome [PubSubJS](https://github.com/mroderick/PubSubJS) library and wonder which one to choose. First of all, both are tiny, have no dependencies, and offer async event broadcasting. The two main features that PubSubES offers are:\n\n1. Auto-unsubscribable event listening: via `pubSub.subscribe(eventName, eventHandler, times)` you can make the `eventHandler` unsubscribed from `eventName` automatically after `eventName` was broadcasted `times` times.\n\n2. Between-context messaging: PubSubES supports the new Broadcast Channel API so you can send events between different browser contexts, e.g., tabs.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflekschas%2Fpub-sub","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fflekschas%2Fpub-sub","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflekschas%2Fpub-sub/lists"}