Stu emitter class
Illiustrating a problem with mutating data set on line 24.
by andfinally
JavaScript
function getSubscriptionSet (emitter, message) {
if (!emitter.subscriptions[message]) {
emitter.subscriptions[message] = []
}
return emitter.subscriptions[message]
}
class Emitter {
constructor () {
this.subscriptions = {}
}
clone () {
return {
emit: this.emit.bind(this),
off: this.off.bind(this),
on: this.on.bind(this),
once: this.once.bind(this)
}
}
emit (message, ...data) {
console.log('NUMBER OF EMITS TO EMIT: ', getSubscriptionSet(this, message).length)
getSubscriptionSet(this, message).forEach(callback => {
console.log('EMITTING')
callback(...data)
})
}
off (message, callback) {
let set = getSubscriptionSet(this, message)
if (callback) {
let index = set.indexOf(callback)
if (index !== -1) set.splice(index, 1)
} else {
set.length = 0
}
}
on (message, callback) {
getSubscriptionSet(this, message).push(callback)
}
once (message, callback) {
console.log('CREATE NEW EMITTER: ', message)
let subscription = (...data) => {
this.off(message, subscription)
callback(...data)
}
this.on(message, subscription)
}
}
const tag = () => {}
const emitter = new Emitter()
emitter.once('bidding finished', () => {
tag()
})
emitter.once('bidding finished', () => {
tag()
})
emitter.once('bidding finished', () => {
tag()
})
emitter.once('bidding finished', () => {
tag()
})
emitter.once('bidding finished', () => {
tag()
})
emitter.once('bidding finished', () => {
tag()
})
emitter.once('bidding finished', () => {
tag()
})
emitter.emit('bidding finished')