Created
January 31, 2018 03:18
-
-
Save leohxj/e868ac580c692f4e815e1965414f59ae to your computer and use it in GitHub Desktop.
Events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyEvents { | |
constructor () { | |
this.events = {} //存储事件监听函数 | |
this.maxListeners = 10 //一种函数类型,最大监听函数数量 | |
} | |
setMaxListeners (maxNum) { | |
this.maxListeners = maxNum | |
} | |
getMaxListeners () { | |
return this.maxListeners | |
} | |
listeners (event) { | |
return this.events[event] | |
} | |
addListener (type, listener) { | |
if (this.events[type]) { | |
if (this.maxListeners != 0 && this.events[type].length > this.maxListeners) { | |
return console.error(`该${type}事件类型的listteners超出限制,使用emitter.setMaxListeners() 来增加添加事件监听数量。`) | |
} | |
this.events[type].push(listener) | |
} else { | |
this.events[type] = [listener] | |
} | |
} | |
once (type, listener) { | |
//执行后立即销毁 | |
let wrapper = (...rest) => { | |
listener.apply(this, rest) | |
this.removeListener(type, wrapper) | |
} | |
this.addListener(type, wrapper) | |
} | |
removeListener (type, listener) { | |
if (this.events[type]) { | |
this.events[type] = this.events[type].filter(ev => { | |
ev != listener | |
}) | |
//抛弃掉等于listener的 | |
} | |
} | |
removeAllListener (type) { | |
delete this.events[type] | |
} | |
emit (type, ...rest) { | |
this.events[type] && this.events[type].forEach(listener => { | |
listener.apply(this, rest) | |
}) | |
} | |
} | |
MyEvents.prototype.on = MyEvents.prototype.addListener | |
module.exports = MyEvents | |
作者:happyGloria | |
链接:https://juejin.im/post/5a6ebc056fb9a01ca072172b | |
来源:掘金 | |
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 |
Author
leohxj
commented
Jan 31, 2018
•
- Simple implementation of EventTarget
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment