Skip to content

Instantly share code, notes, and snippets.

@mach3
Created January 23, 2017 06:10
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 mach3/83dd1c50288ca5eb9a8e2f6574ecc754 to your computer and use it in GitHub Desktop.
Save mach3/83dd1c50288ca5eb9a8e2f6574ecc754 to your computer and use it in GitHub Desktop.
$.fn.on(eventType, selector, selector, handler) みたいな物を。挙動はちょっと異なります。
var _delegate = function(elms, type, selector, callback){
elms = (_type(elms) === "string") ? document.querySelectorAll(elms)
: (! elms.length) ? [elms]
: elms;
Array.from(elms).forEach(function(elm){
elm.addEventListener(type, function(e){
var valid = !! Array.from(this.querySelectorAll(selector))
.filter(function(el){
return el === e.target;
}).length;
if(valid){
callback.call(this, e);
}
}, false);
});
};
_delegate("#container", "click", ".childItem", function(e){
console.log(e.target);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment