【问题标题】:How do I get a reference to an event stream from a within an event handler?如何从事件处理程序中获取对事件流的引用?
【发布时间】:2013-05-06 19:30:26
【问题描述】:

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

【问题讨论】:

    标签: dart dart-webui web-component


    【解决方案1】:

    如果我理解正确,您想知道处理程序中的发送者,对吧?

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

    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&lt;String&gt; 而不是Stream&lt;Map&gt;

    sources.forEach((src) => src.listen((data) => handleEvent(src, data)));
    
    void handleEvent(Connection sender, String data) {
      ...
    }
    

    【讨论】:

    • 非常感谢!我喜欢第二种选择。效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多