Last active
October 25, 2016 16:10
-
-
Save bradyvercher/5428468 to your computer and use it in GitHub Desktop.
Bind event listeners with optional debounce and throttle modes using vanilla JavaScript.
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
/** | |
* Bind event listeners with optional debounce and throttle modes. | |
* | |
* @param {object} el The object to bind an event to. | |
* @param {string} eventType The type of event to listen for. | |
* @param {object} handler The callback handler. | |
* @param {object} options Options to modify behavior. | |
* - delay: Time in milliseconds. Behavior depends on mode. | |
* - init: Whether the handler should be called when registered. Default is false. | |
* - mode: 'debounce' or 'throttle'. Default is false. | |
*/ | |
function bind( el, eventType, handler, options ) { | |
var eventArgs = [ eventType ], | |
callback, doCallback, method, settings, timeoutId; | |
settings = { | |
delay: 0, | |
init: false, // Set to true to fire when registered. | |
mode: false // debounce|throttle | |
}; | |
for ( var o in settings ) { | |
if ( o in options ) { | |
settings[ o ] = options[ o ]; | |
} | |
} | |
doCallback = 'throttle' === settings.mode ? true : false; | |
// Callback wraps the handler to implement debounce/throttle logic. | |
callback = function() { | |
if ( 'throttle' !== settings.mode || doCallback ) { | |
doCallback = false; | |
if ( 'debounce' === settings.mode ) { | |
clearTimeout( timeoutId ); | |
} | |
timeoutId = setTimeout( function() { | |
handler.call( el, eventType ); | |
doCallback = 'throttle' === settings.mode ? true : false; | |
}, settings.delay ); | |
} | |
}; | |
eventArgs.push( callback ); | |
if ( el.addEventListener ) { | |
method = 'addEventListener'; | |
eventArgs.push( false ); // useCapture parameter. | |
} else if ( el.attachEvent) { | |
method = 'attachEvent'; | |
} | |
// Add the event listener. | |
if ( method ) { | |
el[ method ].apply( el, eventArgs ); | |
} | |
// Call the handler immediately. | |
if ( settings.init ) { | |
handler.call( el, eventType ); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment