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
| class EventEmitter { constructor () { this.handles = {} } on (name, cb) { if (!this.handles) this.handles = {} if (!this.handles[name]) this.handles[name] = [] this.handles[name].push(cb) }
emit (name, ...args) { if (this.handles[name]) { for (var i = 0; i < this.handles[name].length; i++) { this.handles[name][i](...args) } } } }
let event = new EventEmitter() event.on('say', function(name) { console.log('hello, ' + name) })
event.emit('say', 'lilei')
|