Skip to content

Instantly share code, notes, and snippets.

@mach3 mach3/delegate.js

Created Jan 23, 2017
Embed
What would you like to do?
$.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
You can’t perform that action at this time.