Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an event delegation in dart SDK?

Tags:

dart

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);.

like image 977
Samuel Hapak Avatar asked Apr 23 '13 11:04

Samuel Hapak


2 Answers

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;
});
like image 75
Alexandre Ardhuin Avatar answered Nov 17 '22 14:11

Alexandre Ardhuin


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));
}
like image 2
Samuel Hapak Avatar answered Nov 17 '22 14:11

Samuel Hapak