npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@markdomkan/in-memory-bus

v2.1.2

Published

A simple event bus for JavaScript & TypeScript

Downloads

197

Readme

InMemoryBus

alt text

Overview

InMemoryBus is a TypeScript class that provides a simple in-memory event bus system. It allows you to register, emit, and manage events within your application. This is particularly useful for implementing a publish-subscribe pattern, where different parts of your application can communicate with each other without being tightly coupled.

Features

  • Event Registration: Register event listeners that can be triggered when an event is emitted.
  • One-Time Event Listeners: Register listeners that are invoked only once for an event and then automatically removed.
  • Event Emission: Emit events with associated data to trigger registered listeners.
  • Asynchronous Event Emission: Emit events and wait for all listeners to complete, either in parallel or sequentially.
  • Event Listener Management: Remove individual listeners or all listeners for a specific event.
  • Event Inspection: Check if an event has listeners, retrieve all listeners for an event, and list all registered events.
  • Event Clearing: Clear all events and listeners.

Installation

To use InMemoryBus, you can copy the class definition into your TypeScript project. There are no external dependencies.

Usage

Basic Example

// Define event types
interface AppEvents {
  userLoggedIn: { userId: string };
  messageReceived: { message: string };
}

// Create an instance of InMemoryBus
const eventBus = new InMemoryBus<AppEvents>();

// Register an event listener
eventBus.on('userLoggedIn', (data) => {
  console.log(`User logged in with ID: ${data.userId}`);
});

// Emit an event
eventBus.emit('userLoggedIn', { userId: '12345' });

// Output: User logged in with ID: 12345

Registering a One-Time Event Listener

eventBus.once('messageReceived', (data) => {
  console.log(`Received message: ${data.message}`);
});

eventBus.emit('messageReceived', { message: 'Hello, World!' });
// Output: Received message: Hello, World!

// Subsequent emissions won't trigger the listener
eventBus.emit('messageReceived', { message: 'Another message' });

Removing Event Listeners

const callback = (data: { userId: string }) => {
  console.log(`User logged in with ID: ${data.userId}`);
};

eventBus.on('userLoggedIn', callback);

// Remove the specific listener
eventBus.off('userLoggedIn', callback);

// Emit the event - callback won't be invoked
eventBus.emit('userLoggedIn', { userId: '12345' });

Clearing All Event Listeners

eventBus.on('userLoggedIn', (data) => console.log(`User: ${data.userId}`));
eventBus.on('messageReceived', (data) => console.log(`Message: ${data.message}`));

// Clear all listeners
eventBus.clear();

// No output as all listeners have been removed
eventBus.emit('userLoggedIn', { userId: '12345' });
eventBus.emit('messageReceived', { message: 'Hello' });

Inspecting Registered Events

// Check if an event has listeners
const hasUserLoggedInListeners = eventBus.hasListeners('userLoggedIn'); // false

// Get all listeners for an event
const listeners = eventBus.getListeners('userLoggedIn'); // undefined or Set<Function>

// Get a list of all registered event names
const eventNames = eventBus.getEventNames(); // []

Asynchronous Event Emission

eventBus.on('userLoggedIn', async (data) => {
  await someAsyncOperation(data.userId);
  console.log(`User logged in: ${data.userId}`);
});

// Emit and wait for all listeners to complete in parallel
await eventBus.emitAwaitAll('userLoggedIn', { userId: '12345' });

// Emit and wait for all listeners to complete sequentially
await eventBus.emitAwaitSerial('userLoggedIn', { userId: '67890' });

API Reference

on<T extends keyof Events>(event: T, callback: (data: Events[T]) => void): void

Registers a callback function to be invoked when the specified event is emitted.

off<T extends keyof Events>(event: T, callback: (data: Events[T]) => void): void

Removes the specified callback from the event's listener set.

offAll<T extends keyof Events>(event: T): void

Removes all listeners for the specified event.

emit<T extends keyof Events>(event: T, data: Events[T]): void

Emits the specified event, triggering all registered listeners with the provided data.

emitAwaitAll<T extends keyof Events>(event: T, data: Events[T]): Promise<void>

Emits the specified event and waits for all listeners to complete their execution in parallel.

emitAwaitSerial<T extends keyof Events>(event: T, data: Events[T]): Promise<void>

Emits the specified event and waits for each listener to complete its execution sequentially.

once<T extends keyof Events>(event: T, callback: (data: Events[T]) => void): void

Registers a one-time listener for the specified event, which is removed after the event is emitted.

clear(): void

Clears all events and their listeners.

getListeners<T extends keyof Events>(event: T): Set<Function> | undefined

Returns the set of listeners registered for the specified event.

hasListeners<T extends keyof Events>(event: T): boolean

Checks if the specified event has any listeners registered.

getEventNames(): string[]

Returns an array of all registered event names.

License

This code is provided as-is with no warranty. Feel free to use it in your projects. Modify and redistribute as you see fit.

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.


This README.md provides a comprehensive guide on how to use the InMemoryBus class, including installation, usage examples, and a detailed API reference.