11

我正在尝试在 Dart中注册 CustomEvent ( https://developer.mozilla.org/en-US/docs/DOM/Event/CustomEvent )。旧代码是:

window.on['foo'].add((e) => print(e.detail));

新的流 API 改变了您注册事件的方式。如何使用新 API 注册 CustomEvents?

4

1 回答 1

9

这个想法是自定义事件的声明和使用方式与内置事件相同。

因此,对于自定义事件,您可以执行以下操作:

class DataGenerator {
   static EventStreamProvider<Event> dataEvent = new EventStreamProvider('data');
}

然后在元素上收听它:

DataGenerator.dataEvent.forTarget(element).listen(...);

一旦支持元素子类化并且事件通常直接在其元素上触发,并且当事件子类化允许自定义事件的更有用的事件类型时,这将变得更清晰。

我们讨论了保留window.on['foo'].listen(...)API,但试图阻止字符串访问器,因为对于某些事件,我们将它们填充为不同的事件名称。

这是一个更完整的示例:

import "dart:html";

DivElement dartDiv;

main() {
  dartDiv = query("#dartDiv");

  // Add a button to generate a CustomEvent called CustomDartEvent.
  var customEventStreamProvider = new EventStreamProvider<CustomEvent>("CustomDartEvent");
  var customEventButton = new ButtonElement()
    ..text = "Generate custom Dart event"
    ..classes.add("gwt-Button")  // For consistency
    ..onClick.listen((e) {
      var detail = {
        "n": 8,
        "s": "Hello from Dart",
        "obj": {
          "hello": "from Dart"          
        }
      };  
      var event = new CustomEvent("CustomDartEvent",
          canBubble: false, cancelable: false, detail: detail);
      window.dispatchEvent(event);
    });
  dartDiv.children.add(customEventButton);

  // Listen for CustomEvents called CustomDartEvent.
  customEventStreamProvider.forTarget(window).listen((e) {
    printString("""
      Received CustomDartEvent:
      type: ${e.type},
      detail: ${e.detail}
    """);
  });
}

void printString(String s) {
  var div = new DivElement()
    ..text = s;
  dartDiv.children.add(div);
}
于 2013-02-11T21:10:08.167 回答