Created
May 12, 2021 11:39
-
-
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.
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 {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