2013-05-12 143 views
2

我需要在我的网页上管理许多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. 
} 

回答

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) { 
    ... 
} 
+0

非常感谢我喜欢第二个选项,它的工作很喜欢一个魅力 – 2013-05-12 19:44:23

+0

不客气。 很高兴我能帮上忙。 – 2013-05-12 19:49:19