Imagine, you want to listen to all clicks made to any anchor element on page. The anchors on page can be dynamically added/removed during the page lifetime and you want to register all of the click events, even on newly added.
Is there any way how to attach delegated event (like in jQuery) in Dart using its standard libraries?
In jQuery you can achieve this with element.on('click', '.selector', handler);
.
You can now do that with ElementStream.matches
like this :
document.body.onClick.matches('.selector').listen((Event event) {
print('Super cool!');
// The currently registered target for the event
// document.body
event.currentTarget;
// The element whose CSS selector matched
// .selector
event.matchingTarget;
// The target to which the event was originally dispatched
// the real element clicked under .selector
event.target;
});
Because I have found no viable solution, I have created package that enables delegation.
You can find it at http://pub.dartlang.org/packages/delegate
Code is simple:
delegate(parent, condition, handler) {
return (event) {
var element = event.target;
while (element != parent && element != null) {
if (condition(element)) {
handler(event, element);
}
element = element.parent;
}
};
}
delegateOn(parent, String eventType, condition, handler) {
parent.on[eventType].listen(delegate(parent, condition, handler));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With