Update
This snippet is now improved and officially an npm module called dom-handler
Update
This snippet is now improved and officially an npm module called dom-handler
What about event delegation?
What about a better question with more content and/or examples?
Ok. How can i do something like (in jquery) $('.element').on('click', '.my-sub-element', callback). i colud see, now possible to do that by something like this:
Handler.add(document.documentElement, {
clickCapture: true,
click: function (e) {
if (e.target.className.match('our-selector-for-check')) { // very simplified check by selector
// handle event
}
}
});
Will be great if i can just specify selector something like:
Handler.add(document.documentElement, {
clickCapture: true,
clickDelegate: '.our-selector-for-check',
click: function (e) {
// handle event
}
});
that's actually not a bad idea at all … but please consider this library rather a proof of concept based on the usage of handleEvent
instead of functions as listener.
Your example, could be either implemented magically behind the scene, or simply with a _delegate
helper, i.e.
Handler.add(document.documentElement, {
_delegated: function (e) {
var target = e.target,
delegate = this[e.type + 'Delegate'];
return !!(target && delegate && target.match(delegate));
},
clickDelegate: '.our-selector-for-check',
click: function (e) {
if (this._delegated(e)) {
// do what's needed to be done
}
}
});
I might consider to take initial code inside a repo and your hint will probably be implemented … until then, feel free to use the code and improve as you wish.
hey @d4rkr00t I'm working on an official repo with tests and improvements, where possible.
I wonder what do you think about this possibility, which is already actually implemented in 0.1.1
Handler.add(document.documentElement, {
clickTarget: '.our-selector-for-check',
click: function (e) {
// do what's needed to be done with
// e.target, the node with class .our-selector-for-check
// or e.currentTarget, which is the initial node
}
});
I've actually made this feature smart enough to recognize one or more handlers, like:
Handler.add($('.list'), {
clickTarget: [
'ul.main',
'ul.main > li'
],
click: function (e) {
// do what's needed to be done with
// outer UL or its nested LI
}
});
Long story short, the explicit intent is to use a different event target
so I found the name more appropriate, and the ability to set more than one target a good idea too.
The default handleEvent
in this case is not the basic one, but one that requires more checks at runtime … still fast enough, and I think a good compromise anyway.
Thoughts ?
the minified version: 309 bytes gzipped (485 bytes uncompressed)