gpt4 book ai didi

dart - 如何从事件处理程序中获取对事件流的引用?

转载 作者:行者123 更新时间:2023-12-03 02:54:18 25 4
gpt4 key购买 nike

我需要在我的网页上管理多个 Web 组件的全局状态。 (例如,每个 Web 组件都有一个“选择”按钮/功能,我会跟踪组件以确保一次只选择一个组件。)

为了管理我的组件的全局状态,每个 Web 组件都向我的主 Web 应用程序中的一个公共(public)处理程序提供一个事件流。不幸的是,我需要我的处理程序知道它是从哪个流/Web 组件调用的,以便管理全局状态。我的处理程序如何获取此信息?

这是我的示例代码:

// _webComponents is a list of references to each component. 
// getStream() gets a stream of events from each component.
// connections is a list of streams from all my web components.
_webComponents.forEach((connection)=>connections.add(connection.getStream()));
connections.forEach((Stream<String> connection)=>connection.listen(eventHandler));


void eventHandler(webComponentEvent){
// ?? How do i find out which web component the event came from ??
// ToDo: use event and web component info to manage a global state of web components.
}

最佳答案

如果我理解正确,您想知道处理程序中的发件人,对吗?

有两种选择。第一个是将发送方作为数据的一部分发送:

class Dog { // controller and stream initialization removed for brevity
Stream get onBark => ...;
void bark(){
// of course, you can have a typed object instead of map
_barkController.add({'sender': this, 'data': 'woof'});
}
}

// attach to source
var dog = new Dog();
dog.onBark.listen((event) {
sender = event['sender'];
data = event['data'];
...
});

另一种选择是在闭包中绑定(bind)发送者。这不需要您更改流的类型(因此您仍将拥有 Stream<String> 而不是 Stream<Map> :

sources.forEach((src) => src.listen((data) => handleEvent(src, data)));

void handleEvent(Connection sender, String data) {
...
}

关于dart - 如何从事件处理程序中获取对事件流的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16510631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com