Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Intercept & release / remove all event listeners. Partially as an easy way to make Mithril router single-SPA compliant.
const {addEventListener} = EventTarget.prototype
export default function EventListenerListener({
blocking = false,
removing = true,
visitor = Function.prototype,
} = {}){
if(this instanceof EventListenerListener){}
else return new EventListenerListener(...arguments)
let capturing = false
let listeners = []
this.capture = () => {
if(capturing)
console.warn('Already capturing')
else {
capturing = true
visitor(this, arguments)
EventTarget.prototype.addEventListener = function(){
if(!blocking)
addEventListener.apply(this, arguments)
listeners.push([this, arguments])
}
}
return this
}
this.release = () => {
if(!capturing)
console.warn('Not capturing')
const captured = listeners.map(x => ({
this : x[0],
arguments: x[1],
}))
capturing = false
listeners = []
return captured
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment