Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created May 12, 2021 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/8d4cef0b1b1c342c07ba9d5353946641 to your computer and use it in GitHub Desktop.
Save barneycarroll/8d4cef0b1b1c342c07ba9d5353946641 to your computer and use it in GitHub Desktop.
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