all files / util/ EventEmitter.js

65.48% Statements 55/84
58.62% Branches 34/58
88.89% Functions 8/9
67.9% Lines 55/81
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218                                    12404×     11158× 11158× 11158× 19104×   19104×   11158×   1246×                                   2395×                     177× 124×   53×                           28514× 1301×   28514×                         2395× 2395× 2395× 1117×     1278×     2395×       2395×         2395×                       65× 53×                 53× 53×   12×                 12× 12×           12×       12× 12× 22× 22× 12× 12×       12×   12× 12×             124× 80×     90× 12×       124×         2407×                             2407×            
import forEach from './forEach'
import isObject from './isObject'
 
// for debugging
const DEBUG = false
let count = 0
const COUNT_MSG = '%s listeners registered in the whole system.'
 
/**
  Event support.
*/
class EventEmitter {
 
  /**
    Emit an event.
 
    @param {String} event
    @param ...arguments
    @return true if a listener was notified, false otherwise.
   */
  emit(event) {
    if (event in this.__events__) {
      // console.log("Emitting event %s (%d listeners) on", event, this.__events__[event].length, this)
      // Clone the list of bindings so that handlers can remove or add handlers during the call.
      var bindings = this.__events__[event].slice()
      var args = Array.prototype.slice.call(arguments, 1)
      for (var i = 0, len = bindings.length; i < len; i++) {
        var binding = bindings[i]
        // console.log("- triggering %s on %s", event, binding.context.constructor.name)
        binding.method.apply(binding.context, args)
      }
      return true
    }
    return false
  }
 
  /**
    Subscribe a listener to an event.
 
    Optionally, a `priority` can be provided to control the order
    of all bindings. The default priority is 0. All listeners with the
    same priority remain in order of registration.
    A lower priority will make the listener be called later, a higher
    priority earlier.
 
    @param {String} event
    @param {Function} method
    @param {Object} context
   */
  on(event, method, context) {
    // TODO: we could add options like 'once'
    _on.call(this, event, method, context)
  }
 
  /**
    Unsubscribe a listener from an event.
 
    @param {String} event
    @param {Function} method
    @param {Object} context
   */
  off(event, method, context) { // eslint-disable-line no-unused-vars
    if (arguments.length === 1 && isObject(arguments[0])) {
      _disconnect.call(this, arguments[0])
    } else {
      _off.apply(this, arguments)
    }
  }
 
  _debugEvents() {
    /* eslint-disable no-console */
    console.log('### EventEmitter: ', this)
    forEach(this.__events__, (handlers, name) => {
      console.log("- %s listeners for %s: ", handlers.length, name, handlers)
    })
    /* eslint-enable no-console */
  }
 
  get __events__() {
    if (!this.___events___) {
      this.___events___ = {}
    }
    return this.___events___
  }
 
}
 
/*
  Internal implementation for registering a listener.
 
  @param {String} event
  @param {Function} method
  @param {Object} context
 */
function _on(event, method, context) {
  /* eslint-disable no-invalid-this */
  var bindings
  validateMethod( method, context )
  if (this.__events__.hasOwnProperty(event)) {
    bindings = this.__events__[event]
  } else {
    // Auto-initialize bindings list
    bindings = this.__events__[event] = []
  }
  // Add binding
  bindings.push({
    method: method,
    context: context || null
  })
  Iif (DEBUG) {
    count++
    console.info('_on()', event, method.name, context, this)
    console.info(COUNT_MSG, count)
  }
  return this
  /*eslint-enable no-invalid-this */
}
 
/*
  Remove a listener.
 
  @param {String} event
  @param {Function} method
  @param {Object} context
 */
function _off(event, method, context) {
  /* eslint-disable no-invalid-this */
  if (arguments.length === 0) {
    Iif (DEBUG) {
      forEach(this.__events__, (bindings) => {
        bindings.forEach((b) => {
          console.info('_off()', b.method.name, b.context, this)
        })
        count -= bindings.length
      })
      console.info(COUNT_MSG, count)
    }
    this.___events___ = {}
    return this
  }
  Iif (arguments.length === 1) {
    // Remove all bindings for event
    if (DEBUG) {
      count -= (this.__events__[event] || []).length
      console.info(COUNT_MSG, count)
    }
    delete this.__events__[event]
    return this
  }
  validateMethod(method, context)
  Iif (!(event in this.__events__) || !this.__events__[event].length) {
    if (DEBUG) console.info('NO MATCHING BINDINGS')
    // No matching bindings
    return this
  }
  // Default to null context
  Iif (arguments.length < 3) {
    context = null
  }
  // Remove matching handlers
  let bindings = this.__events__[event]
  for (let i = bindings.length-1; i >= 0; i--) {
    const b = bindings[i]
    if (b.method === method && b.context === context) {
      bindings.splice(i, 1)
      Iif (DEBUG) count--
    }
  }
  // Cleanup if now empty
  if (bindings.length === 0) {
    delete this.__events__[event]
  }
  Iif (DEBUG) console.info(COUNT_MSG, count)
  return this
  /* eslint-enable no-invalid-this */
}
 
// removes a listener from all events
function _disconnect(context) {
  /* eslint-disable no-invalid-this */
  // Remove all connections to the context
  forEach(this.__events__, (bindings, event) => {
    for (let i = bindings.length-1; i>=0; i--) {
      // bindings[i] may have been removed by the previous steps
      // so check it still exists
      if (bindings[i] && bindings[i].context === context) {
        _off.call(this, event, bindings[i].method, context)
      }
    }
  })
  return this
  /* eslint-enable no-invalid-this */
}
 
function validateMethod(method, context) {
  // Validate method and context
  Iif (typeof method === 'string') {
    // Validate method
    if (context === undefined || context === null) {
      throw new Error( 'Method name "' + method + '" has no context.' )
    }
    if (!(method in context)) {
      // Technically the method does not need to exist yet: it could be
      // added before call time. But this probably signals a typo.
      throw new Error( 'Method not found: "' + method + '"' )
    }
    if (typeof context[method] !== 'function') {
      // Technically the property could be replaced by a function before
      // call time. But this probably signals a typo.
      throw new Error( 'Property "' + method + '" is not a function' )
    }
  } else Iif (typeof method !== 'function') {
    throw new Error( 'Invalid callback. Function or method name expected.' )
  }
}
 
export default EventEmitter