Is there event delegation in the dart SDK?

Imagine that you want to listen to all the clicks made for any anchor element on the page. Anchors on a page can be dynamically added / removed over the life of the page, and you want to register all click events, even when adding new ones.

Is there a way to associate a delegated event (e.g. in jQuery) in Dart using its standard libraries?

In jQuery, you can achieve this with element.on('click', '.selector', handler); .

+6
source share
2 answers

Now you can do it with ElementStream.matches as follows:

 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; }); 
+7
source

Since I did not find a viable solution, I created a package that allows delegation.

You can find it at http://pub.dartlang.org/packages/delegate

The 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)); } 
+2
source

Source: https://habr.com/ru/post/943432/


All Articles