Skip to content

Instantly share code, notes, and snippets.

@SeanJM
Last active December 9, 2015 15:32
Show Gist options
  • Save SeanJM/19806e549ae952247c02 to your computer and use it in GitHub Desktop.
Save SeanJM/19806e549ae952247c02 to your computer and use it in GitHub Desktop.
an event binder
function control (node) {
var hookMatch = /^-js-[a-zA-Z-\_]+|\s-js-[a-zA-Z-\_]+/g;
function jsCase(string) {
return string.match(/[a-zA-Z0-9_]+/g).map(function (a, i) {
if (i === 0) {
return a.toLowerCase();
}
return a[0].toUpperCase() + a.substr(1, a.length).toLowerCase();
}).join('');
}
function trimBinder(name) {
return jsCase(name.trim().replace(/-js-/, ''));
}
function list(filter) {
var nodeList = [].slice.call(node.querySelectorAll('[class*="-js-"]'));
nodeList = nodeList.filter(function (node) {
return /(\s-js-[a-z])|^-js-[a-z]/.test(node.className);
}).map(function (node) {
return {
node : node,
binder : node.className.match(hookMatch).map(trimBinder)
}
});
if (typeof filter === 'string') {
nodeList = nodeList.filter(function (nodeListItem) {
return nodeListItem.binder.indexOf(filter) !== -1;
});
}
return nodeList;
}
function keys(object) {
var keysList = [];
for (var k in object) {
keysList.push(k);
}
return keysList;
}
function assign(a, b) {
for (var k in b) {
a[k] = b[k];
}
return a;
}
function setBind(node, eventName, binderFunction) {
if (/Key$/.test(eventName)) {
node.addEventListener('keyup', function (e) {
var keypress = eventName.match(/^(esc|enter)/)[1];
var which = {
enter : 13,
esc : 27
};
if (e.which === which[keypress]) {
binderFunction(assign({
trigger : node
}, e));
}
}, false);
} else {
node.addEventListener(eventName, function (e) {
binderFunction(assign({
trigger : node
}, e));
}, false);
}
}
function bind(settings) {
list().forEach(function (bindInfo) {
bindInfo.binder.forEach(function (binderName) {
keys(settings[binderName]).forEach(function (eventName) {
setBind(bindInfo.node, eventName, settings[binderName][eventName]);
});
});
});
}
return {
bind : bind,
list : list,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment