Open leeword opened 3 years ago
class Event { constructor() { this.eventList = Object.create(null); } $on(event, fn) { (this.eventList[event] || (this.eventList[event] = [])).push(fn); } $off(event, fn) { let fns = this.eventList[event]; if (!fns) return false; if (!fn) { fns.length = 0; } else { const fnIndex = fns.indexOf(fn); if (fnIndex >= 0) { fns.splice(fnIndex, 1); } } } $once(event, fn) { const onceWrapper = (...args) => { this.$off(event, onceWrapper); fn.apply(this, args); } this.$on(event, onceWrapper); } $trigger(event, ...args) { const fns = this.eventList[event]; if (!fns) return false; fns.forEach(fn => fn.apply(this, args)); } } export default Event;