【问题标题】:Unsuscribe every handler of an event取消订阅事件的事件处理程序
【发布时间】:2014-01-22 08:31:29
【问题描述】:

我们可以在一次通话中取消对流的所有订阅吗?

在大多数dart示例中,我们可以看到取消订阅的主要方式是直接从StreamSubscription调用Cancel方法,但是我们需要存储这些Subscriptions...

var s = myElement.onClick.listen(myHandler); //storing the sub
s.Cancel() //unsuscribing the handler

有没有办法取消给定流的每个订阅而不存储它们?

可能看起来像这样的东西:

myElement.onClick.subscriptions.forEach((s)=> s.Cancel());

【问题讨论】:

    标签: events event-handling dart


    【解决方案1】:

    使用装饰器模式:

    class MyStream<T> implements Stream<T>{
    
        Stream<T> _stream;
    
        List<StreamSubscription<T>> _subs;
    
        /*
           use noSuchMethod to pass all calls directly to _stream,
           and simply override the call to listen, and add a new method to removeAllListeners
        */
    
        StreamSubscription<T> listen(handler){
           var sub = _stream.listen(handler);
           _subs.add(sub);
           return sub;
        }
    
        void removeAllListeners(){
           _subs.forEach((s) => s.cancel());
           _subs.clear();
        }
    }
    

    如果您想在 html 元素上使用它,您可以通过装饰 ElementMyElement 上执行完全相同的装饰器模式。示例:

    class MyElement implements Element{
    
        Element _element;
    
        /*
            use noSuchMethod to pass all calls directly to _element and simply override
            the event streams you want to be able to removeAllListeners from
        */
    
        MyElement(Element element){
            _element = element;
            _onClick = new MyStream<MouseEvent>(_element.onClick);
        }
    
        MyStream<MouseEvent> _onClick;
        MyStream<MouseEvent> get onClick => _onClick; //override the original stream getter here :)
    }
    

    然后相应地使用:

    var superDivElement = new MyElement(new DivElement());
    superDivElement.onClick.listen(handler);
    
    //...
    
    superDivElement.onClick.removeAllListeners();
    

    【讨论】:

      【解决方案2】:

      您必须存储引用才能取消事件。

      【讨论】:

        猜你喜欢
        • 2012-06-15
        • 2021-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多