This repository has been archived by the owner on Dec 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
/
emitter.js
69 lines (52 loc) · 1.62 KB
/
emitter.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
/*
Emitter
*/"use strict"
var indexOf = require("mout/array/indexOf"),
forEach = require("mout/array/forEach")
var prime = require("./index"),
defer = require("./defer")
var slice = Array.prototype.slice;
var Emitter = prime({
constructor: function(stoppable){
this._stoppable = stoppable
},
on: function(event, fn){
var listeners = this._listeners || (this._listeners = {}),
events = listeners[event] || (listeners[event] = [])
if (indexOf(events, fn) === -1) events.push(fn)
return this
},
off: function(event, fn){
var listeners = this._listeners, events
if (listeners && (events = listeners[event])){
var io = indexOf(events, fn)
if (io > -1) events.splice(io, 1)
if (!events.length) delete listeners[event];
for (var l in listeners) return this
delete this._listeners
}
return this
},
emit: function(event){
var self = this,
args = slice.call(arguments, 1)
var emit = function(){
var listeners = self._listeners, events
if (listeners && (events = listeners[event])){
forEach(events.slice(0), function(event){
var result = event.apply(self, args)
if (self._stoppable) return result
})
}
}
if (args[args.length - 1] === Emitter.EMIT_SYNC){
args.pop()
emit()
} else {
defer(emit)
}
return this
}
})
Emitter.EMIT_SYNC = {}
module.exports = Emitter