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
| class Event { constructor() { this.clientMap = {}; this.cacheMap = {}; } listen(key, fn) { if (!this.clientMap[key]) { this.clientMap[key] = [] }
this.clientMap[key].push(fn);
if (this.cacheMap[key] && this.cacheMap[key].length) { this.cacheMap[key].forEach(cacheFn => { cacheFn.call(this, key) }); this.cacheMap[key] = null; } } emit(key, ...args) { const fns = this.clientMap[key]; if (!fns || fns.length === 0) {
if (!this.cacheMap[key]) { this.cacheMap[key] = [] } constcacheFn = () => { returnthis.emit(key, ...args) } this.cacheMap[key].push(cacheFn) return false; }
fns.forEach((fn) => { fn.apply(this, args); }); } remove(key, fn) { const fns = this.clientMap[key] if (!fn) { fns && (this.clientMap[key].length = 0) } fns.forEach((item, index) => { if (fn === item || fn.name === item.name || fn === item.fn) { fns.splice(index, 1) } }) } once(key, fn) { let _this = this; function on() { _this.remove(key, on); fn.apply(_this, arguments); } on.fn = fn; _this.emit(key, on); return _this; } }
const MessageEvent = new Event();
MessageEvent.emit('create', 'notify')
MessageEvent.listen('create', function create(name) { console.log('event', name); })
MessageEvent.listen('beforeCreated', function beforeCreated(name) { console.log('beforeCreated', name); })
MessageEvent.emit('beforeCreated', 'notify')
|