GithubHelp home page GithubHelp logo

pwfoo / nanoevents Goto Github PK

View Code? Open in Web Editor NEW

This project forked from ai/nanoevents

0.0 1.0 0.0 4.23 MB

Simple and tiny (72 bytes) event emitter library for JavaScript

License: MIT License

JavaScript 6.86% TypeScript 93.14%

nanoevents's Introduction

Nano Events

Simple and tiny event emitter library for JavaScript.

  • Only 97 bytes (minified and gzipped). It uses Size Limit to control size.
  • on method returns unbind function. You don’t need to save callback to variable for removeListener.
  • TypeScript and ES modules support.
  • No aliases, just emit and on methods. No Node.js EventEmitter compatibility.
import { createNanoEvents } from 'nanoevents'

const emitter = createNanoEvents()

const unbind = emitter.on('tick', volume => {
  summary += volume
})

emitter.emit('tick', 2)
summary //=> 2

unbind()
emitter.emit('tick', 2)
summary //=> 2
Sponsored by Evil Martians

Table of Contents

Install

npm install nanoevents

TypeScript

Nano Events accepts interface with event name to listener argument types mapping.

interface Events {
  set: (name: string, count: number) => void,
  tick: () => void
}

const emitter = createNanoEvents<Events>()

// Correct calls:
emitter.emit('set', 'prop', 1)
emitter.emit('tick')

// Compilation errors:
emitter.emit('set', 'prop', '1')
emitter.emit('tick', 2)

Mixing to Object

Because Nano Events API has only just 2 methods, you could just create proxy methods in your class or encapsulate them entirely.

class Ticker {
  constructor () {
    this.emitter = createNanoEvents()
    this.internal = setInterval(() => {
      this.emitter.emit('tick')
    }, 100)
  }

  stop () {
    clearInterval(this.internal)
    this.emitter.emit('stop')
  }

  on (event, callback) {
    return this.emitter.on(event, callback)
  }
}

With Typescript:

import { createNanoEvents, Emitter } from "nanoevents"

interface Events {
  start: (startedAt: number) => void
}

class Ticker {
  emitter: Emitter

  constructor () {
    this.emitter = createNanoEvents<Events>()
  }

  on<E extends keyof Events>(event: E, callback: Events[E]) {
    return this.emitter.on(event, callback)
  }
}

Add Listener

Use on method to add listener for specific event:

emitter.on('tick', number => {
  console.log(number)
})

emitter.emit('tick', 1)
// Prints 1
emitter.emit('tick', 5)
// Prints 5

In case of your listener relies on some particular context (if it uses this within itself) you have to bind required context explicitly before passing function in as a callback.

var app = {
  userId: 1,
  getListener () {
    return () => {
      console.log(this.userId)
    }
  }
}
emitter.on('print', app.getListener())

Note: binding with use of the .bind() method won’t work as you might expect and therefore is not recommended.

Remove Listener

Methods on returns unbind function. Call it and this listener will be removed from event.

const unbind = emitter.on('tick', number => {
  console.log('on ' + number)
})

emitter.emit('tick', 1)
// Prints "on 1"

unbind()
emitter.emit('tick', 2)
// Prints nothing

Execute Listeners

Method emit will execute all listeners. First argument is event name, others will be passed to listeners.

emitter.on('tick', (a, b) => {
  console.log(a, b)
})
emitter.emit('tick', 1, 'one')
// Prints 1, 'one'

Events List

You can get used events list by events property.

const unbind = emitter.on('tick', () => { })
emitter.events //=> { tick: [ [Function] ] }

Once

If you need add event listener only for first event dispatch, you can use this snippet:

class Ticker {
  constructor () {
    this.emitter = createNanoEvents()
  }
  
  once (event, callback) {
    const unbind = this.emitter.on(event, (...args) => {
      unbind()
      callback(...args)
    })
    return unbind
  }
}

Remove All Listeners

emitter.on('event1', () => { })
emitter.on('event2', () => { })

emitter.events = { }

nanoevents's People

Contributors

ai avatar dependabot[bot] avatar subzey avatar gwer avatar 38elements avatar nulltier avatar ben-eb avatar trysound avatar dan-lee avatar dharkness avatar posva avatar ifiokjr avatar jrobichaud avatar mnasyrov avatar azu avatar

Watchers

 avatar

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.