2014-01-22 51 views
4

我们可以在一次调用中取消每个流的订阅吗?Unsuscribe事件的每个处理程序

在大多数镖的例子,我们可以看到,以unsuscribe的主要途径是调用StreamSubscription取消直接方法,但我们需要存储这些订阅...

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

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

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

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

回答

4

使用Decorator模式。例如:

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(); 
1

你必须存储参考,以便能够取消事件。如果你想通过装饰Element使用这个HTML元素,你可以做一个MyElement一模一样的装饰图案

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(); 
    } 
}