forked from ai/nanoevents
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (90 loc) · 2.17 KB
/
index.js
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
(
/**
* Interface for event subscription.
*
* @example
* var NanoEvents = require('nanoevents')
*
* class Ticker {
* constructor() {
* this.emitter = new NanoEvents()
* }
* on() {
* return this.emitter.on.apply(this.events, arguments)
* }
* tick() {
* this.emitter.emit('tick')
* }
* }
*
* @alias NanoEvents
* @class
*/
module.exports = function NanoEvents () {
/**
* Event names in keys and arrays with listeners in values.
* @type {object}
*
* @example
* Object.keys(ee.events)
*
* @alias NanoEvents#events
*/
this.events = { }
}
).prototype = {
/**
* Add a listener for a given event.
* @param {string} event The event name.
* @param {function} cb The listener function.
*
* @return {function} Unbind listener from event.
*
* @example
* const unbind = ee.on('tick', (tickType, tickDuration) => {
* count += 1
* })
*
* disable () {
* unbind()
* }
*
* @alias NanoEvents#on
* @method
*/
on: function on (event, cb) {
if (process.env.NODE_ENV !== 'production' && typeof cb !== 'function') {
throw new Error('Listener must be a function')
}
// event variable is reused and repurposed, now it's an array of handlers
event = this.events[event] = this.events[event] || []
event.push(cb)
return function () {
// a.splice(i >>> 0, 1) === if (i !== -1) a.splice(i, 1)
// -1 >>> 0 === 0xFFFFFFFF, max possible array length
event.splice(event.indexOf(cb) >>> 0, 1)
}
},
/**
* Calls each of the listeners registered for a given event.
*
* @param {string} event The event name.
* @param {...*} arguments The arguments for listeners.
*
* @returns {undefined}
*
* @example
* ee.emit('tick', tickType, tickDuration)
*
* @alias NanoEvents#emit
* @method
*/
emit: function emit (event) {
var list = this.events[event]
if (!list || !list[0]) return // list[0] === Array.isArray(list)
var args = list.slice.call(arguments, 1)
list.slice().map(function (i) {
i.apply(this, args) // this === global or window
})
}
}