Skip to content

Instantly share code, notes, and snippets.

@francisbrito
Created October 20, 2015 01:35
Show Gist options
  • Save francisbrito/27252c23b08887b9ccd8 to your computer and use it in GitHub Desktop.
Save francisbrito/27252c23b08887b9ccd8 to your computer and use it in GitHub Desktop.
Demonstrative snippet showing how small, focused functions can abstract implementation details
const selector = '[data-list] [data-scroll-thing]';
function onKeyPressed(event) {
if (isIgnoredKey(event)) return;
const target = event.target;
const letter = getSanitizedLetterFromKey(event.keyCode);
if (!letter) return;
let scrollContainer = getParentElementMatchingSelector(target, selector);
if (!scrollContainer || !isEventTargetAnInputElement(target)) {
let scrollContainers = findElementsMatching(selector);
if (scrollContainers && scrollContainers.length === 1) {
scrollContainer = getFirstScrollContainer(scrollContainers);
}
}
if (scrollContainer) {
const uriParent = getParentElementMatchingSelector(
scrollContainer, '[data-uri]'
);
if (!uriParent) return;
const uri = getDataAttributeFromElement('uri', uriParent);
if (!uri) return;
if (!uriUtils.isValid(uri)) return;
dispatchEvent('letter-jump-request', scrollContainer, uri, letter);
}
}
function isIgnoredKey(ev) {
return ev.metaCtrl || ev.ctrlKey;
}
function getSanitizedLetterFromKey(keyCode) {
String.fromCharCode(keyCode).trim().toLowerCase();
}
function getParentElementMatchingSelector(childElement, selector) {
return $(target).parent(selector);
}
function isEventTargetAnInputElement(target) {
return $(target).matches('input', 'textarea');
}
function findElementsMatching(selector) {
return $(document).find(selector);
}
function getFirstScrollContainer(containers) {
return $(containers[0]);
}
function getDataAttributeFromElement(attribute, element) {
return $(element).data(attribute);
}
function dispatchEvent(eventName, ..eventArgs) {
const dispatcherArgs = [eventName].concat(eventArgs);
centralDispatch.apply(dispatcherArgs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment