2014-01-22 52 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(); 
    } 
}