{"id":23084068,"url":"https://github.com/lilbunnyrabbit/event-emitter","last_synced_at":"2026-02-10T21:32:23.658Z","repository":{"id":265244960,"uuid":"895458781","full_name":"lilBunnyRabbit/event-emitter","owner":"lilBunnyRabbit","description":"A lightweight and type-safe EventEmitter implementation for TypeScript.","archived":false,"fork":false,"pushed_at":"2025-02-18T22:36:07.000Z","size":41,"stargazers_count":0,"open_issues_count":3,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-30T17:06:42.925Z","etag":null,"topics":["event-emitter","event-system","npm-package","type-safe","typescript","typescript-library"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/@lilbunnyrabbit/event-emitter","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/lilBunnyRabbit.png","metadata":{"files":{"readme":"README.md","changelog":null,"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}},"created_at":"2024-11-28T08:49:57.000Z","updated_at":"2025-02-18T22:35:46.000Z","dependencies_parsed_at":null,"dependency_job_id":"2093eab4-7851-46ac-a3dd-82a1cc4fa47d","html_url":"https://github.com/lilBunnyRabbit/event-emitter","commit_stats":null,"previous_names":["lilbunnyrabbit/event-emitter"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lilBunnyRabbit%2Fevent-emitter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lilBunnyRabbit%2Fevent-emitter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lilBunnyRabbit%2Fevent-emitter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lilBunnyRabbit%2Fevent-emitter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lilBunnyRabbit","download_url":"https://codeload.github.com/lilBunnyRabbit/event-emitter/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251723013,"owners_count":21633062,"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":["event-emitter","event-system","npm-package","type-safe","typescript","typescript-library"],"created_at":"2024-12-16T15:48:13.393Z","updated_at":"2026-02-10T21:32:23.558Z","avatar_url":"https://github.com/lilBunnyRabbit.png","language":"TypeScript","funding_links":["https://github.com/sponsors/lilBunnyRabbit"],"categories":[],"sub_categories":[],"readme":"# EventEmitter\n\n[![npm version](https://img.shields.io/npm/v/@lilbunnyrabbit/event-emitter.svg)](https://www.npmjs.com/package/@lilbunnyrabbit/event-emitter)\n[![npm downloads](https://img.shields.io/npm/dt/@lilbunnyrabbit/event-emitter.svg)](https://www.npmjs.com/package/@lilbunnyrabbit/event-emitter)\n\nThe `EventEmitter` class provides a powerful and flexible mechanism for managing and handling custom events,\nsimilar in functionality to the standard [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/EventTarget) interface found in web APIs.\nThis class allows for easy creation of event-driven architectures in [TypeScript](https://www.typescriptlang.org/) applications, enabling objects to publish events to which other parts of the application can subscribe. It's particularly beneficial in scenarios where you need to implement custom event logic or when working outside of environments where [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/EventTarget) is not available or suitable.\n\nWith `EventEmitter`, you can define event types, emit events, and dynamically attach or detach event listeners,\nall within a type-safe and intuitive API.\n\n## Installation\n\nTo use this package in your project, run:\n\n```sh\nnpm i @lilbunnyrabbit/event-emitter\n```\n\n## Usage\n\n### Creating an `EventEmitter`\n\nStart by creating an instance of the `EventEmitter` class.\nYou can define the types of events it will handle using a [TypeScript](https://www.typescriptlang.org/) interface.\n\n```ts\ntype MyEvents = {\n  data: string;\n  loaded: void;\n  error: Error;\n}\n\nconst emitter = new EventEmitter\u003cMyEvents\u003e();\n```\n\n### Registering Event Listeners\n\nTo listen for events, use the `EventEmitter.on` method.\nDefine the event type and provide a callback function that will be executed when the event is emitted.\n\n```ts\nemitter.on(\"data\", (data: string) =\u003e {\n  console.log(\"Data\", data);\n});\n\nemitter.on(\"loaded\", function () {\n  console.log(\n    \"Emitter loaded\",\n    this // EventEmitter\u003cMyEvents\u003e\n  );\n});\n\nemitter.on(\"error\", (error: Error) =\u003e {\n  console.error(`Error: ${error.message}`);\n});\n```\n\n#### Registering a Global Listener\n\nIf you want to listen for **all** events with a single callback, use `EventEmitter.onAll`. The listener function receives an object containing the event type and any associated data:\n\n```ts\nemitter.onAll((event: GlobalEvent\u003cMyEvents\u003e) =\u003e {\n  console.log(`Global listener caught event of type \"${String(event.type)}\"`, event.data);\n});\n```\n\nThis is especially useful when you need to handle different event types in one centralized place.\n\n### Removing Event Listeners\n\nYou can remove a specific event listener by using the `EventEmitter.off` method,\nspecifying the event type and the listener to remove.\n\n```ts\nconst onError = (error: Error) =\u003e console.error(error);\n\nemitter.on(\"error\", onError);\n\n// ...\n\nemitter.off(\"error\", onError);\n```\n\n#### Removing a Global Listener\n\nTo remove the callback you registered via `EventEmitter.onAll`, call `EventEmitter.offAll` with the same function:\n\n```ts\nconst globalListener = (event: GlobalEvent\u003cMyEvents\u003e) =\u003e {\n  console.log(`Event \"${String(event.type)}\"`, event.data);\n};\n\nemitter.onAll(globalListener);\n\n// ...\n\nemitter.offAll(globalListener);\n```\n\n#### Removing All Listeners\n\nIf you need to remove **all** listeners (both event-specific and global) at once, you can use the `clear` method:\n\n```ts\nemitter.clear(); // Removes all event listeners and global listeners\n```\n\nAfter calling `EventEmitter.clear`, no existing listeners will be triggered unless you re-register them.\n\n### Emitting Events\n\nUse the `EventEmitter.emit` method to trigger an event.\nThis will invoke all registered listeners for that event type.\n\n```ts\nemitter.emit(\"data\", \"Sample data\");\nemitter.emit(\"loaded\");\nemitter.emit(\"error\", new Error(\"Oh no!\"));\n```\n\n### Extending `EventEmitter`\n\nFor more specialized use cases, you can extend the `EventEmitter` class.\nThis allows you to create a custom event emitter with additional methods or properties tailored to specific needs.\nWhen extending, you can still take full advantage of the type safety and event handling features of the base class.\n\n```ts\ntype MyServiceEvents = {\n  dataLoaded: string;\n  error: Error;\n}\n\n// Extending the EventEmitter class\nclass MyService extends EventEmitter\u003cMyServiceEvents\u003e {\n  // Custom method\n  loadData() {\n    try {\n      // Load data and emit a `dataLoaded` event\n      const data = \"Sample Data\";\n      this.emit(\"dataLoaded\", data);\n    } catch (error) {\n      // Emit an `error` event\n      this.emit(\"error\", error);\n    }\n  }\n}\n\nconst service = new MyService();\n\nservice.on(\"dataLoaded\", function (data) {\n  console.log(\n    `Data loaded: ${data}`,\n    this // MyService\n  );\n});\n\nservice.on(\"error\", (error) =\u003e console.error(`Error: ${error.message}`));\n\n// Using the custom method\nmyEmitter.loadData();\n```\n\nIn this example, `MyService` extends the `EventEmitter` class, adding a custom method `loadData`.\nThis method demonstrates how to `EventEmitter.emit` `dataLoaded` and `error` events,\nintegrating the event-emitting functionality into a more complex operation.\n\n## Documentation\n\nIf you're looking for detailed API docs, check out the [full documentation](./docs/globals.md) generated via [Typedoc](https://typedoc.org/).\n\n## Development\n\nThis section provides a guide for developers to set up the project environment and utilize various npm scripts defined in the project for efficient development and release processes.\n\n### Setting Up\n\nClone the repository and install dependencies:\n\n```sh\ngit clone https://github.com/lilBunnyRabbit/event-emitter.git\ncd event-emitter\nnpm install\n```\n\n### NPM Scripts\n\nThe project includes several npm scripts to streamline common tasks such as building, testing, and cleaning up the project.\n\n| Script              | Description                                                                                                                                                                                       | Command                 |\n| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |\n| **`build`**         | Compiles the [TypeScript](https://www.typescriptlang.org/) source code to JavaScript, placing the output in the `dist` directory. Essential for preparing the package for publication or testing. | `npm run build`         |\n| **`test`**          | Executes the test suite using [Jest](https://jestjs.io/). Crucial for ensuring that your code meets all defined tests and behaves as expected.                                                    | `npm test`              |\n| **`clean`**         | Removes both the `dist` directory and the `node_modules` directory. Useful for resetting the project's state during development or before a fresh install.                                        | `npm run clean`         |\n| **`changeset`**     | Manages versioning and changelog generation based on conventional commit messages. Helps prepare for a new release by determining which parts of the package need version updates.                | `npm run changeset`     |\n| **`release`**       | Publishes the package to npm. Uses `changeset publish` to automatically update package versions and changelogs before publishing. Streamlines the release process.                                | `npm run release`       |\n| **`generate:docs`** | Generates project documentation using [Typedoc](https://typedoc.org/). Facilitates the creation of comprehensive and accessible API documentation.                                                | `npm run generate:docs` |\n\nThese scripts are designed to facilitate the development process, from cleaning and building the project to running tests and releasing new versions. Feel free to use and customize them as needed for your development workflow.\n\n## Contribution\n\nContributions are always welcome! For any enhancements or bug fixes, please open a pull request linked to the relevant issue. If there's no existing issue related to your contribution, feel free to create one.\n\n## Support\n\nYour support is greatly appreciated! If this package has been helpful, consider supporting its development. Your contributions help maintain and improve this project.  \n\n[![GitHub Sponsor](https://img.shields.io/static/v1?label=Sponsor\u0026message=%E2%9D%A4\u0026logo=GitHub\u0026color=%23fe8e86)](https://github.com/sponsors/lilBunnyRabbit)\n\n## License\n\nMIT © Andraž Mesarič-Sirec","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flilbunnyrabbit%2Fevent-emitter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flilbunnyrabbit%2Fevent-emitter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flilbunnyrabbit%2Fevent-emitter/lists"}