dart如何创建,收听和发出自定义事件?

Ots*_*lal 10 dart

我有这样的课:

class BaseModel {
  Map objects;

  // define constructor here

  fetch() {
    // fetch json from server and then load it to objects
    // emits an event here
  }

}
Run Code Online (Sandbox Code Playgroud)

就像backbonejs我想在我的视图中change调用fetch并创建change事件监听器时发出一个事件.

但是从阅读文档,我不知道从哪里开始,因为有很多指向事件,如Event Events EventSource等等.

你们能给我一个暗示吗?

Set*_*add 18

我假设您要发出不需要存在dart:html库的事件.

您可以使用Streams API公开事件流,供其他人监听和处理.这是一个例子:

import 'dart:async';

class BaseModel {
  Map objects;
  StreamController fetchDoneController = new StreamController.broadcast();

  // define constructor here

  fetch() {
    // fetch json from server and then load it to objects
    // emits an event here
    fetchDoneController.add("all done"); // send an arbitrary event
  }

  Stream get fetchDone => fetchDoneController.stream;

}
Run Code Online (Sandbox Code Playgroud)

然后,在你的应用程序中:

main() {
  var model = new BaseModel();
  model.fetchDone.listen((_) => doCoolStuff(model));
}
Run Code Online (Sandbox Code Playgroud)

使用本机Streams API很不错,因为这意味着您不需要浏览器来测试您的应用程序.

如果您需要发出自定义HTML事件,可以看到以下答案:https://stackoverflow.com/a/13902121/123471