Last active
May 30, 2019 06:21
-
-
Save vinicius5581/898cdf730af7b36108fae8216bb9fe84 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
class Emitter { | |
constructor (events = []) { | |
this.events = new Map(events) | |
} | |
on (name, cb) { | |
this.events.set(name, [...(this.events.get(name) || []), cb]) | |
return () => this.events.set(name, this.events.get(name).filter(fn => fn !== cb)) | |
} | |
once (name, cb) { | |
let unsubscribe; | |
const onceCb = (...args) => { | |
cb(...args) | |
unsubscribe() | |
} | |
unsubscribe = this.on( name, onceCb ) | |
return unsubscribe | |
} | |
trigger (name, ...args) { | |
return this.events.has(name) && this.events.get(name).map(fn => fn(...args)) | |
} | |
} | |
// func | |
const pubSub = () => { | |
const events = new Map(); | |
const sub = (name,cb) => { | |
events.set(name, (events.get(name) || new Set()).add(cb)); | |
return () => events.get(name).delete(cb); | |
}; | |
return { | |
sub, | |
emit: (name,...args) => { | |
events.has(name) && events.get(name).forEach(cb => cb(...args)); | |
}, | |
once: (name,cb) => { | |
let unsub; | |
const newcb = (...args) => { | |
unsub(); | |
cb(...args); | |
} | |
return unsub = sub(name, newcb); | |
} | |
}; | |
} | |
const ps = pubSub(); | |
const fn1 = () => console.log(1) | |
const fn2 = (msg) => console.log(msg) | |
const fn3 = (msg, msg2) => console.log(msg + msg2) | |
const fn4 = () => console.log('Only once') | |
const offSubChangeFn1 = ps.sub('change', fn1) | |
const offSubChangeFn2 = ps.sub('change', fn2) | |
const offSubChangeFn3 = ps.sub('change', fn3) | |
const offSubceChangeFn4 = ps.once('change', fn4) | |
offSubChangeFn3() | |
offSubceChangeFn4() | |
ps.emit('change', 'hello', ' world') | |
const ee = new Emitter(); | |
const offOnChangeFn1 = ee.on('change', fn1) | |
const offOnChangeFn2 = ee.on('change', fn2) | |
const offOnChangeFn3 = ee.on('change', fn3) | |
const offOnceChangeFn4 = ee.once('change', fn4) | |
offOnChangeFn3() | |
ee.trigger('change', 'hello', ' world') | |
/* | |
class EventEmitter { | |
constructor() { | |
this.events = {}; | |
} | |
on(eventName, callback) { | |
this.events[eventName] = this.events[eventName] || []; | |
this.events[eventName].push(callback) | |
} | |
off(eventName, callback) { | |
if (this.events[eventName]) { | |
for (let i = 0; i < this.events[eventName].length; i++) { | |
if (this.events[eventName][i] === callback) { | |
this.events[eventName].splice(i,1); | |
break; | |
} | |
} | |
} | |
} | |
trigger(eventName, ...rest) { | |
this.events[eventName].forEach(fn => fn(...rest)) | |
} | |
} | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment