How do I listen for custom events in Dart?

2019-02-08 12:25发布

问题:

I want to do something like

// 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"));

Is it possible? How? I've been searching on Google for a few hours now, but I'm kind of new to programming in general, so I don't really know any keywords for this sort of thing.

Thanks! :)

-- EDIT: Solved --

Here's how to pass arguments along (The editor will complain, but it works)

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

:-)

回答1:

This should work:

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

See the docs:

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


回答2:

You said you wanted to pass around data. Let's assume we have this class:

class Person {
    String name;
    int age;
}

then this listener:

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

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

All we need to pass data around is to write something like:

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

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

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

This is the way to do it. See the documentation:

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


标签: dart