Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created February 7, 2017 15:40
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/9998e9816486d5e63925691cbbae739e to your computer and use it in GitHub Desktop.
Save barneycarroll/9998e9816486d5e63925691cbbae739e to your computer and use it in GitHub Desktop.
A 'do what I mean' addEventListener / removeEventListener interface. Heavily overloaded intuition signature. Returns an object with an off handle to remove all listeners thus added.
const supports = {
capture : false,
passive : false,
once : false
}
try {
document.addEventListener( 'test', null, {
get capture(){ supports.capture = true },
get passive(){ supports.passive = true },
get once(){ supports.once = true },
} )
}
catch( e ){}
function listen( target, event, handler = Function.prototype, options = false ){
const { capture, passive, once } = options
let wrapper = handler
function off(){
target.removeEventListener( event, wrapper, options )
}
if( typeof options === object ){
if( once && !supports.once )
wrapper = function(){
off()
return handler.apply( this, arguments ) || passive
}
if( capture && !supports.capture )
options = true
}
return { off }
}
function slice( list, start, end ){
return Array.prototype.slice.call( list, start, end )
}
function offal( listeners ){
return {
off : () => listeners.map( ( { off } ) => off() )
}
}
export default function on( target, event, handler, options ){
return (
Array.isArray( target )
? offall( target.map( args =>
on.call( this, ...args, slice( arguments, 1 ) )
) )
: Array.isArray( event )
? offall( event.map( args =>
on.call( this, target, ...args, slice( arguments, 2 ) )
) )
: typeof event == 'object'
? offall( Object.keys( event ).map( event =>
on.call( this, target, event, arguments[ 1 ][ event ], slice( arguments, 2 ) )
) )
: event.includes( ' ' )
? offall( event.split( ' ' ).map( event =>
on.call( this, target, event, slice( arguments, 2 ) )
) )
: Array.isArray( handler )
? offall( handler.map( handler =>
on.call( this, target, event, handler, slice( arguments, 3 ) )
) )
: Array.isArray( options )
? listen.call( this, target, event, handler, options[ 0 ] )
: listen.apply( this, arguments )
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment