Skip to content
프로젝트

소개

간단하고 작은(107바이트) JavaScript 이벤트 이미터 라이브러리

개발 도구

이 수치를 측정하는 방법

측정된 스타 증가

in 24h
-1
in 7 days
0
in 15 days
+2
in 1 month
+4

서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.

README.md

Original

Nano Events

Simple and tiny event emitter library for JavaScript.

  • Only 108 bytes (minified and brotlied). It uses Size Limit to control size.
  • The 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

  Nano Events is built by Evil Martians, an American design and engineering consultancy for developer tools, AI, and cybersecurity startups.


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 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

The on method 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 to add an 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 = {}

Usage With Frameworks

You can use Nano Events with front-end frameworks. Below is an example of a custom hook implementation in React.

// hooks/use-on-emit.js

import { useEffect, useRef } from 'react'

export function useOnEmit(emitter, event, cb) {
  const cbRef = useRef(cb)

  useEffect(() => {
    cbRef.current = cb
  }, [cb])

  useEffect(() => {
    const listener = (...args) => cbRef.current(...args)

    const unbind = emitter.on(event, listener)
    return unbind
  }, [emitter, event])
}

// hooks/use-on-emit.d.ts
import type { Emitter, EventsMap } from 'nanoevents'

export declare function useOnEmit<
  Events extends EventsMap,
  Event extends keyof Events
>(emitter: Emitter<Events>, event: Event, cb: Events[Event]): void

Then in the components:

import { createNanoEvents } from 'nanoevents'
import { useOnEmit } from '../hooks/use-on-emit.js'
import { useState } from 'react'

const emitter = createNanoEvents()

export function Counter() {
  const [count, setCount] = useState(0)

  useOnEmit(emitter, 'increment', () => {
    setCount(v => v + 1)
  })

  return <span>{count}</span>
}

export function Increment() {
  return <button onClick={() => emitter.emit('increment')}>Increment</button>
}

관련 프로젝트 살펴보기

불러오는 중…