Created
July 25, 2016 14:20
-
-
Save SaulDoesCode/b85aa0ba2788daefcba182015fcc8d96 to your computer and use it in GitHub Desktop.
self standing event system
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
const eventSystem = (obj = {}) => { | |
const listeners = new Map; | |
function makeHandle(type, func) { | |
const eventsys = this; | |
return { | |
off() { | |
eventsys.off(type, func); | |
return this; | |
}, | |
on() { | |
this.off(); | |
eventsys.on(type, func); | |
return this; | |
}, | |
once() { | |
eventsys.once(type, func); | |
return this; | |
} | |
} | |
} | |
let esMethods = { | |
hasListener(type, func) { | |
return listeners.has(type) && listeners.get(type).has(func); | |
}, | |
addListener(type, func) { | |
if (!listeners.has(type)) listeners.set(type, new Set); | |
listeners.get(type).add(func); | |
}, | |
removeListener(type, func) { | |
if (listeners.has(type)) { | |
const typeGroup = listeners.get(type); | |
if (typeGroup.has(func)) typeGroup.delete(func); | |
if (typeGroup.size == 0) listeners.delete(type); | |
} | |
}, | |
on(type, func) { | |
this.addListener(type, func); | |
return makeHandle(type, func); | |
}, | |
once(type, func) { | |
if (this.hasListener(type, func)) this.removeListener(type, func); | |
const wrap = (...args) => { | |
func.apply(obj,args); | |
this.removeListener(type, wrap); | |
} | |
this.addListener(type, wrap); | |
return makeHandle(type, func); | |
}, | |
off(type, func) { | |
this.removeListener(type, func); | |
return makeHandle(type, func); | |
}, | |
emit(type) { | |
if (listeners.has(type)) { | |
const typeGroup = listeners.get(type); | |
if (typeGroup.size != 0) { | |
const args = Array.prototype.slice.call(arguments, 1); | |
typeGroup.forEach(Listener => { | |
Listener.apply(obj, args); | |
}); | |
} | |
} | |
} | |
}; | |
Object.keys(esMethods).map(method => { | |
obj[method] = esMethods[method]; | |
}); | |
esMethods = null; | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment