mitt

repository·main·Indexed 11 days ago

https://github.com/developit/mitt

A microscopic (under 200 bytes gzipped) functional event emitter and pubsub library for the browser and any JavaScript runtime. Version 3.0.1 provides a familiar API similar to Node's EventEmitter, featuring .on(), .off(), and .emit() methods, support for a '*' wildcard listener, and TypeScript type inference for event payloads.

Tokens
2.1K
Snippets
8
Records
14
Agent score
46%

What's inside mitt

  1. How wildcard '*' events work

    main

    Mitt supports a wildcard '*' event type that allows you to listen to every event fired by the emitter.

    When a handler is registered with '*', it is invoked with two arguments: the type of the event and the evt payload. During an .emit(type, evt) call, the '*' handlers are invoked after the handlers specifically matched to the type.

    Note: You cannot manually fire '*' handlers; they are only triggered as a side effect of emitting other event types.

    emitter.on('*', (type, e) => console.log(type, e))
    emitter.emit('foo', { data: 123 })
    // Logs: 'foo', { data: 123 }
  2. Use Mitt with TypeScript

    main

    Mitt provides excellent type inference for event payloads. To get the best experience, set "strict": true in your tsconfig.json.

    You can define an interface/type representing your events and pass it as a generic to mitt<Events>().

    Alternatively, you can explicitly type the instance using the Emitter type.

    import mitt, { Emitter } from 'mitt';
    
    type Events = {
      foo: string;
      bar?: number;
    };
    
    // Option 1: Inferred via generic
    const emitter = mitt<Events>();
    
    // Option 2: Explicitly typed
    const emitter2: Emitter<Events> = mitt<Events>();
    
    // Usage with type safety
    emitter.on('foo', (e) => {}); // 'e' is inferred as string
    emitter.emit('foo', 42);     // Error: Argument of type 'number' is not assignable to 'string'
  3. Install Mitt

    main

    You can install Mitt via npm to use it in your Node.js or bundler-based projects (like Webpack or Rollup).

    ES6 Modules

    import mitt from 'mitt'

    CommonJS

    var mitt = require('mitt')

    UMD (Browser)

    Include the script via unpkg to access window.mitt:

    <script src="https://unpkg.com/mitt/dist/mitt.umd.js"></script>
    $ npm install --save mitt
  4. Basic Usage of Mitt

    main

    Mitt is a functional event emitter. You can create an instance, listen for specific events, listen to all events using a wildcard, and fire events.

    • Use .on(type, handler) to subscribe.
    • Use .off(type, handler) to unsubscribe.
    • Use .emit(type, evt) to trigger an event.
    • Use the '*' wildcard to listen to all events. When using '*', the handler receives (type, evt).
    • Use .all.clear() to remove all registered handlers.
    import mitt from 'mitt'
    
    const emitter = mitt()
    
    // listen to an event
    emitter.on('foo', e => console.log('foo', e) )
    
    // listen to all events
    emitter.on('*', (type, e) => console.log(type, e) )
    
    // fire an event
    emitter.emit('foo', { a: 'b' })
    
    // clearing all events
    emitter.all.clear()
    
    // working with handler references:
    function onFoo() {}
    emitter.on('foo', onFoo)   // listen
    emitter.off('foo', onFoo)  // unlisten
  5. Unregister event handlers with off()

    main

    Use off(type, handler) to remove listeners.

    • Remove a specific handler: Pass both the type and the exact handler function reference.
    • Remove all handlers for a type: Pass only the type. This will clear all listeners registered for that specific event name.
    • Remove wildcard handlers: Pass '*' as the type to remove wildcard listeners.
    const handler = (foo: string) => console.log(foo);
    
    emitter.on('foo', handler);
    
    // Remove only this specific handler
    emitter.off('foo', handler);
    
    // Remove ALL handlers for 'foo'
    emitter.off('foo');
    
    // Remove wildcard handlers
    emitter.off('*');
  6. Register event handlers with on()

    main

    Use on(type, handler) to register a listener for a specific event type.

    • Specific events: Provide the event name and a handler function that accepts the event payload.
    • Wildcard events: Use the special '*' type to listen to all events. Wildcard handlers receive two arguments: the type of the event and the event payload.

    Note: If you use a wildcard handler, the type argument in the handler will be the name of the event that was triggered.

    type Events = {
      foo: string;
    };
    
    const emitter = mitt<Events>();
    
    // Specific handler
    emitter.on('foo', (foo) => {
      console.log(foo);
    });
    
    // Wildcard handler
    emitter.on('*', (type, event) => {
      console.log(type, event);
    });
  7. Trigger events with emit()

    main

    Use emit(type, event) to trigger an event and execute its registered handlers.

    • Type-matched handlers: Handlers registered for the specific type are invoked first.
    • Wildcard handlers: Handlers registered with '*' are invoked after type-matched handlers. They receive the type and the event payload.

    Note: You cannot manually fire '*' handlers; they only trigger as a side effect of emitting a specific event type.

    type Events = {
      foo: string;
    };
    
    const emitter = mitt<Events>();
    
    emitter.on('foo', (foo) => {
      console.log('Specific:', foo);
    });
    
    emitter.on('*', (type, event) => {
      console.log('Wildcard:', type, event);
    });
    
    emitter.emit('foo', 'bar');
    // Output:
    // Specific: bar
    // Wildcard: foo bar
  8. Access the underlying handler map via all

    main
    The all property on the returned Emitter object provides direct access to the EventHandlerMap. This map contains the event types as keys and their corresponding lists of handlers as values. This can be useful for inspecting the current state of registered listeners or for providing a pre-existing map to the mitt() factory function.
  9. Initialize mitt with type safety

    main

    To use mitt, import the default function and provide a type definition that maps event names (EventType) to their payload types. This ensures that on, off, and emit are type-safe based on your specific event schema.

    EventType can be a string or a symbol.

    import mitt from 'mitt';
    
    type Events = {
      apple: string;
      banana: number;
    };
    
    const emitter = mitt<Events>();
  10. API Reference: .emit(type, evt)

    main

    Invoke all handlers for the given type.

    Parameters:

    • type (string | symbol): The event type to invoke.
    • evt (Any): The value passed to each handler (an object is recommended).

    Note: If '*' handlers are registered, they are invoked after the type-matched handlers. Manually firing '*' handlers is not supported.

  11. API Reference: .on(type, handler)

    main

    Register an event handler for the given type.

    Parameters:

    • type (string | symbol): The type of event to listen for. Use '*' to listen to all events.
    • handler (Function): The function to call in response to the event.