如何监听在DART自定义事件?(How do I listen for custom events

2019-07-05 10:09发布

我想这样做

// WARNING: this code does not work, it's illustrative
query("#myBtn").onClick.listen((e) {
  window.fire["foo"];
});

window.on["foo"].listen((e) => print("foo was here"));

window.on["foo"].listen((e) => print("and here"));

可能吗? 怎么样? 我一直在寻找,现在谷歌上了几个小时,但我是一种新的编程一般,所以我真的不知道这种事的关键字。

谢谢! :)

- 编辑:解决 -

以下是如何传递下去参数(编辑会抱怨,但它的工作原理)

List<String> myData = ["one","two"];

query("#myBtn").onClick.listen((e) {
  window.on["foo"].dispatch(new CustomEvent("foo", canBubble: false, cancelable: false, detail: myData));
});

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

:-)

Answer 1:

这应该工作:

window.on['foo'].listen((e) => print("foo was here"));

请参阅该文档:

  • http://api.dartlang.org/docs/releases/latest/dart_html/Events.html


Answer 2:

你说你想绕过数据。 假设我们有这样的类:

class Person {
    String name;
    int age;
}

那么这个监听器:

window.on['foo'].listen((e) {
  Person p = e.detail;

  print(p.name); // Jack
});

所有我们需要来回传递数据是写类似:

var p = new Person()
  ..name = 'Jack'
  ..age = 25;

var e = new CustomEvent('foo', detail: p);

window.on['foo'].dispatch(e);

这是做它的方式。 查看文档:

  • http://api.dartlang.org/docs/releases/latest/dart_html/Events.html
  • http://api.dartlang.org/docs/releases/latest/dart_html/CustomEvent.html


文章来源: How do I listen for custom events in Dart?
标签: dart