Skip to content

Instantly share code, notes, and snippets.

@itsliamjones
Last active August 15, 2016 15:56
Show Gist options
  • Save itsliamjones/e605e785dadd97a4a239d68e187e17c2 to your computer and use it in GitHub Desktop.
Save itsliamjones/e605e785dadd97a4a239d68e187e17c2 to your computer and use it in GitHub Desktop.
Example register for click delegation
function ClickRegister(global, parent, debug) {
var parent = parent || document,
debug = !!debug,
register = [];
var action = function (event) {
var target = event.target || event.srcElement;
if (debug) {
console.group("click register debugging");
console.log(event);
console.log(target);
console.groupEnd();
}
for (var i = register.length - 1; i >= 0; i--) {
if (target.matches(register[i].condition)) {
register[i].func.apply(this, [event, target]);
break; // Are we allowing multiple events per condition?
}
}
};
if (parent.addEventListener) {
parent.addEventListener("click", action, false);
} else if (parent.attachEvent) {
parent.attachEvent("onclick", action);
} else {
throw "Unable to add event listener to parent element";
}
return {
register: function (condition, func) {
if (typeof condition !== "string") {
throw "condition must be a string";
}
if (func.length !== 2) {
throw "argument 2 must be an instance of function that accepts two arguments (event, target)";
}
register.push(
{
condition: condition,
func: func
}
);
},
deregister: function (condition) {
register = register.filter( function (v, k) {
return v.condition !== condition;
}, condition);
},
getAll: function () {
return register;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment