Skip to content

Instantly share code, notes, and snippets.

@yy-dev7
Last active January 9, 2018 04:03
Show Gist options
  • Save yy-dev7/266eb76fecc056e1885651d8fc72bee5 to your computer and use it in GitHub Desktop.
Save yy-dev7/266eb76fecc056e1885651d8fc72bee5 to your computer and use it in GitHub Desktop.
Observer
class EventEmitter {
constructor() {
this.clientList = {}
}
on(key, fn) {
if (!this.clientList[key]) {
this.clientList[key] = []
}
this.clientList[key].push(fn)
}
emit(key, ...args) {
let fns = this.clientList[key]
if (!fns || !fns.length) {
return false
}
for (let i = 0, fn; fn = fns[i++];) {
fn.apply(this, args)
}
}
removeListener(key, fn) {
const fns = this.clientList[key]
if (!fns || !fn) {
return
}
for (let i = fns.length; i--;) {
if (fns[i] === fn) {
fns.splice(i, 1)
}
}
}
removeAllListeners(key) {
if (key) {
this.clientList[key].length = 0
} else {
this.clientList = {}
}
}
once(key, fn) {
function on(...args) {
this.removeListener(key, on)
fn.apply(this, args)
}
return this.on(key, on)
}
}
const event = new EventEmitter()
event.once('key2', function(...args) {
console.log('once-key2', args)
})
event.emit('key2', 'world')
event.emit('key2', 'world')
event.emit('key2', 'world')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment