简体   繁体   中英

How do I listen for custom events in Dart?

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

:-)

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:

This should work:

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

See the docs:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM