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

@ortense/mediator

v1.3.0

Published

A minimal implementation for a dependency-free event broker with internal context for front-end

Downloads

73

Readme

Mediator banner - the mediator mascot generated by dall-e 2

@ortense/mediator

install size Coverage Status

A minimalistic and dependency-free event mediator with internal context for front-end. Written typescript for a good development experience and really light, just 300 bytes in your bundle!

Access the complete documentation at ortense.github.io/mediator/

Use case

You want to simplify communication between independent components in your web app. The mediator can be used to facilitate the exchange of data and events between different parts of the application without crate a strong coupling, keeping the separation of concerns between the components of your app or external integrations like third party scripts or extensions.

Mediator flow chart - made in excalidraw.com

Install

Pick your favorite package manager.

npm install @ortense/mediator  # npm
yarn add  @ortense/mediator    # yarn
pnpm add @ortense/mediator     # pnpm
bun add @ortense/mediator      # bun

Usage

First, define an interface that extends MediatorContext to represent your context, this interface must be an object with properties serializable to JSON.

export interface MyContext extends MediatorContext {
  value: string
  active: boolean
  nested: {
    items: number[]
  }
}

Now create an object to be your initial context.

const initialContext: MyContext = {
  value: 'hello world',
  active: true,
  nested: {
    items: [],
  },
}

Then create the mediator object:

export const myMediator = createMediator(initialContext)

The complete setup file should look like this:

import { MediatorContext, createMediator } from '@ortense/mediator'

export interface MyContext extends MediatorContext {
  value: string
  active: boolean
  nested: {
    items: number[]
  }
}

const initialContext: MyContext = {
  value: 'hello world',
  active: true,
  nested: {
    items: [],
  },
}

export const myMediator = createMediator(initialContext)

Events

The mediator use simple strings to identify events, think of it as a unique identifier to be used to send or listen to events.

Optionally, you can define a type that extends from string to represent the events that your mediator has.

type MyEvents = 'loaded' | 'value:change' | 'item:added' | 'item:removed'

export const myMediator = createMediator<MyContext, MyEvents>(initialContext)

This is a good practice to help developers who will interact with the mediator, providing predictability of the events that can be listened or send.

Listening to events

To listen to events use the .on method

import { myMediator, MyContext } from './my-mediator'

function myEventListener(ctx: Readonly<MyContext>, event: MyEvents) {
  // do what you want
}

myMediator.on('loaded', myEventListener)

If you prefer you could use the type MediatorEventListener

import { MediatorEventListener } from '@ortense/mediator'
import { myMediator, MyContext, MyEvents } from './my-mediator'

const myEventListener: MediatorEventListener<MyContext, MyEvents> = (ctx, event) => {
  // do what you want
}

myMediator.on('loaded', myEventListener)

You also use the wildcard * to listen all events.

myMediator.on('*', (ctx, event) => console.log(ctx, event))

Wildcard listeners could be useful for debugging, for example logging whenever an event is triggered.

myMediator.on('*', (ctx, event) => {
  console.log(`Event ${event} change the context to`, ctx)
})

To stop use the .off method

myMediator.off('loaded', myEventListener)

Send events

To send events use the .send method.

import { myMediator} from './my-mediator'

myMediator.send('loaded')

All listener functions for the loaded event will be called in the order they were added to the mediator.

The .send method could receive a function to modifiy the context:

import { myMediator, MyContext } from './my-mediator'

function changeValue(ctx: Readonly<MyContext>) {
  return {
    value: 'new value'
  }
}

myMediator.send('value:change', changeValue)

If you prefer you could use the MediatorContextModifier type.

import { MediatorContextModifier } from '@ortense/mediator'
import { myMediator, MyContext } from './my-mediator'

const changeValue: MediatorContextModifier<MyContext> = (ctx) => ({
  value: 'new value'
})

myMediator.send('value:change', changeValue)

Or an inline declaration:

import { myMediator } from './my-mediator'

myMediator.send('value:change', (ctx) => ({ ...ctx, active: 'new value }))

Get current context

Use the method .getContext to get a readonly version of the current context.

import { myMediator } from './my-mediator'

const ctx = myMediator.getContext() //? Readonly<MyContext>