dart如何创建,收听和发出自定义事件? [英] dart how to create, listen, and emits custom event?
问题描述
我有这样的类:
class BaseModel {
Map objects;
// define constructor here
fetch() {
// fetch json from server and then load it to objects
// emits an event here
}
}
像 backbonejs
我想在调用 fetch
并创建侦听器时发出 change
事件我认为是 change
事件。
Like backbonejs
i want to emits a change
event when i call fetch
and create a listener for change
event on my view.
但是从阅读文档开始,我不知道从哪里开始有太多指向事件的信息,例如 Event
Events
EventSource
依此类推。
But from reading the documentation, i don't know where to start since there are so many that points to event, like Event
Events
EventSource
and so on.
你们能给我一个提示吗?
Can you guys give me a hint?
推荐答案
我假设您要发出不需要 dart:html
库存在的事件。
I am assuming you want to emit events that do not require the presence of dart:html
library.
您可以使用Streams API公开事件流,以供其他人侦听和处理。例如:
You can use the Streams API to expose a stream of events for others to listen for and handle. Here is an example:
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;
}
然后,在您的应用程序中:
Then, over in your app:
main() {
var model = new BaseModel();
model.fetchDone.listen((_) => doCoolStuff(model));
}
使用本机Streams API很不错,因为这意味着您不需要浏览器以测试您的应用程序。
Using the native Streams API is nice because it means you don't need the browser in order to test your application.
如果需要发出自定义HTML事件,则可以看到以下答案: https://stackoverflow.com/a/13902121/123471
If you are required to emit a custom HTML event, you can see this answer: https://stackoverflow.com/a/13902121/123471
这篇关于dart如何创建,收听和发出自定义事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!