Skip to content

Instantly share code, notes, and snippets.

@lxynox
Last active June 22, 2019 08:56
Show Gist options
  • Save lxynox/22aec78d49c3c30184a4f9d2891d880a to your computer and use it in GitHub Desktop.
Save lxynox/22aec78d49c3c30184a4f9d2891d880a to your computer and use it in GitHub Desktop.
tiny event emitter

Definition

'use strict'

function createEmitter() {
  let evtHandlersMap = {}
  
  // @evt [String] event name
  // @handler [Function] event handlers
  // @options [Object] options passed to event handlers
  function emit (evt, options) {
    const handlers = evtHandlersMap[evt]
    if (handlers) {
      handlers.forEach(handler => handler(options))
    }
  }
  function on (evt, handler) {
    !evtHandlersMap[evt] && evtHandlersMap[evt] = []
    evtHandlersMap[evt].push(handler.bind(this))
  }
  
  return {
    emit,
    on
  }
}

export default createEmitter()

Usage

import {emit} from './emitter.js'

export default function (target, opts = {}) {
  if (!opts || typeof opts !== 'object') {
    return
  }
  const keys = Object.keys(opts)
  for (const key of keys) {
    if (key reserved) {
      target.addEventListener(EVENT_TYPE, (e) => {
        emit(EVENT_TYPE)
        opts[key]()
      })
    } else {
      // customized ...
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment