Giter Site home page Giter Site logo

vitorluizc / event-emitter Goto Github PK

View Code? Open in Web Editor NEW
17.0 3.0 1.0 132 KB

Emit and listen events in any class, object or function without messing them extending classes. And you can declare it with Fluent Interfaces or tree-shakeable functions.

License: MIT License

TypeScript 93.95% JavaScript 6.05%
event-emitter emitter typescript

event-emitter's Introduction

@bitty/event-emitter

License Library minified size Library minified + gzipped size

Emit and listen events in any class, object or function without messing them extending classes.

Event emitters can be created from any class, object or function. And you can handle them with Fluent Interfaces or tree-shakeable functions.

  • ๐Ÿ“ฆ Distributions in ESM, CommonJS, UMD and UMD minified formats.

    • Supports both Node.js ESM (import/export) and CommonJS (require/module.exports).
    • Supports browsers and CDNs with UMD and minified formats.
  • โšก Lightweight:

    • It's bundled using rollup.js.
    • Smaller than 1.2kB (minified and gzipped).
    • Supports tree shaking.
  • ๐Ÿ”‹ Bateries included:

    • No dependencies.
    • It isn't based on es2015+ or newer browser features, you just need WeakMap and Map.
      • You can polyfill them.
  • โœ… Safe:

    • Type declarations for IDEs and editor's autocomplete/intellisense.
    • Made with TypeScript as strict as possible.
    • Unit tests with AVA.

Installation

This library is published in the NPM registry and can be installed using any compatible package manager.

npm install @bitty/event-emitter --save

# For Yarn, use the command below.
yarn add @bitty/event-emitter

Installation from CDN

This module has an UMD bundle available through JSDelivr and Unpkg CDNs.

<!-- Using default bundle from JSDelivr -->
<script src="https://cdn.jsdelivr.net/npm/@bitty/event-emitter"></script>

<!-- Using default bundle from UNPKG -->
<script src="https://unpkg.com/@bitty/event-emitter"></script>

<script>
  /**
   * UMD bundle exposes library API through `EventEmitter` object.
   */
  const emitter = EventEmitter.createEventEmitter(window);

  emitter.once('add-product-to-cart', (product) => {
    // ...
  });

  EventEmitter.emit(window, 'add-product-to-cart', '2x Banana');
</script>

API

createEventEmitter

Creates an EventEmitter using target as reference.

import { createEventEmitter } from '@bitty/event-emitter';

const emitter = createEventEmitter(window);

EventEmitter

An interface that implements emit, off, on and once methods in specified target. Its created by createEventEmitter function.

import type { EventEmitter } from '@bitty/event-emitter';

interface Product {
  name: string;
  // ...
}

interface CartEvents {
  'add-product-to-cart': Product;
  'remove-product-from-cart': Product;
  'increase-product-count': [Product, number];
}

let emitter: EventEmitter<CartEvents>;

emitter
  .on('add-product-to-cart', (product) => { /* ... */ })
  .on('increase-product-count', ([product, count]) => { /* ... */ })
  .once('remove-product-to-cart', (product) => { /* ... */ });

emitter.emit('add-product-to-cart', {
  name: 'Banana',
  // ...
});

emit

Execute event handlers attached to event name with payload as argument.

import { emit } from '@bitty/event-emitter';

emit(window, 'user-sign-in', null);

off

Detach event handler from event name.

import { off } from '@bitty/event-emitter';

function onUserSignIn(user) {
  // ...
}

off(window, 'user-sign-in', onUserSignIn);

Detach all event handlers from event name, if no event handler is received.

import { off } from '@bitty/event-emitter';

off(window, 'user-sign-in');

Detach all event handlers from all event names, if no event name is received.

import { off } from '@bitty/event-emitter';

off(window);

on

Attach event handler to event name.

import { on } from '@bitty/event-emitter';

function onAddProductToCart(product) {
  // ...
}

on(window, 'add-product-to-cart', onAddProductToCart);

once

Same as on, but event handler can only be executed once.

import { once } from '@bitty/event-emitter';

function onUserSignOut(user) {
  // ...
}

once(window, 'user-sign-out', onUserSignOut);

Usage with TypeScript

You can use same way as JavaScript. But to provide type-safe events, you need to create an event dictionary interface/type.

Event dictionaries are structures with event names as property names and payloads are values. Event emitter will correct type-check and correlate them.

interface UserEvents {
  rename: {
    from: string;
    to: string;
  };

  delete: {
    deletedAt: Date;
  };
}

const user = {
  name: 'Bruce Wayne'
};

const emitter = createEventEmitter<UserEvents>(user);

emitter.on('any-other-event-name', () => console.log('Not working'));
//=> โŒ you can only use "rename" and "delete" event names.

emitter.once('rename', ({ from, to }) => {
  console.log(`User was renamed from "${from}" to "${to}".`);
});
//=> โœ” "rename" is a valid event name, and { from, to } is its payload.

emitter.emit('rename', {
  from: 'Bruce Wayne',
  to: 'Batman'
});
//=> โœ” Type-safe event emission.

License

Released under MIT License.

event-emitter's People

Contributors

vitorluizc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

mechamobau

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.