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

时间:2013-05-12 18:21:24

标签: dart dart-webui web-component

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

要管理组件的全局状态,每个Web组件都会向我的主Web应用程序中的公共处理程序提供事件流。不幸的是,我需要我的处理程序知道它是从哪个流/ 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.
}

1 个答案:

答案 0 :(得分:3)

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

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

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'];
   ...
});

另一种选择是在闭包中绑定发件人。这不需要您更改流的类型(因此您仍然会Stream<String>而不是Stream<Map>

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

void handleEvent(Connection sender, String data) {
  ...
}
相关问题