class EventEmitter { constructor(name) { this.name = name this.events = {} }
on (name, callback) { if (name === 'newListener') { callback() } const callbacks = this.events[name] || [] callbacks.push(callback) this.events[name] = callbacks }
off (name, callback) { const callbacks = this.events[name] || [] callbacks = callbacks.filter(fn=> fn !== callbacks) this.events[name] = callbacks }
emit(name, ...args) { const callbacks = this.events[name] || [] callbacks.forEach(cb=> cb(args)) }
once(name, callback) { function wrap(...args) { callback(args) this.off(name, callback) } this.on(name, wrap) } }
const events = new EventEmitter()
events.on("newListener", function(eventName){ console.log(`eventName`, eventName) })
const event = new EventEmitter() const handle = (...pyload) => console.log(pyload);
event.on("click", handle) event.emit("click", 100, 200, 300, 100) event.remove("click", handle)
event.once("dbclick", function() { console.log("click") })
event.emit("dbclick", 100)
|