-
Notifications
You must be signed in to change notification settings - Fork 66
/
events.js
60 lines (48 loc) · 1.42 KB
/
events.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
var Scuttlebutt = require('./')
var inherits = require('util').inherits
var each = require('iterate').each
var u = require('./util')
var EventEmitter = require('events').EventEmitter
module.exports = ReliableEventEmitter
inherits(ReliableEventEmitter, Scuttlebutt)
function ReliableEventEmitter (opts) {
if(!(this instanceof ReliableEventEmitter)) return new ReliableEventEmitter(opts)
Scuttlebutt.call(this, opts)
}
var emit = EventEmitter.prototype.emit
var emitter = ReliableEventEmitter.prototype
emitter.emit = function (event) {
if(event === '__proto__')
throw new Error('__proto__ is illegal event name')
var args = [].slice.call(arguments)
if(event == 'newListener')
return emit.apply(this, args)
return this.localUpdate(args)
}
var on = EventEmitter.prototype.on
emitter.on = function (event, listener) {
if(event === '__proto__')
throw new Error('__proto__ is invalid event')
return on.call(this, event, listener)
}
emitter.applyUpdate = function (update) {
var key = update[0][0]
this.events = this.events || {}
this.events[key] = this.events[key] || []
this.events[key].push(update)
//emit the event.
emit.apply(this, update[0])
return true
}
emitter.history = function (filter) {
var self = this
var h = []
this.events = this.events || {}
each(this.events, function (es) {
each(es, function (e) {
if(u.filter(e, filter))
h.push(e)
})
})
return u.sort(h)
}