Skip to content

Instantly share code, notes, and snippets.

@vasergen
Created July 12, 2016 09:48
Show Gist options
  • Save vasergen/321e280f9f2112a3f86bbefb4ce18fec to your computer and use it in GitHub Desktop.
Save vasergen/321e280f9f2112a3f86bbefb4ce18fec to your computer and use it in GitHub Desktop.
let observerDecorator = (function () {
let eventList = {}
return function (obj) {
obj.addEvent = (event, fn) => {
if(!eventList[event]) {
eventList[event] = []
}
if(eventList[event].indexOf(fn) === -1) {
eventList[event].push(fn)
}
}
obj.dispatchEvent = (event) => {
if(!eventList[event]) {
return
}
for(let fn of eventList[event]) {
fn()
}
}
}
})()
class Worker {}
class Boss {}
//
let worker = new Worker()
let boss = new Boss()
observerDecorator(worker)
observerDecorator(boss)
let salary = () => {
console.log('thank you boss!')
}
worker.addEvent('salary', salary)
worker.addEvent('salary', salary)
boss.dispatchEvent('salary')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment