2017-04-25 18 views
0

我有一個週期性觸發的事件:Bacon.interval如何停止?

let periodicEvent = Bacon.interval(1000, {}); 
periodicEvent.onValue(() => { 
    doStuff(); 
}); 

我想是暫停和重啓periodicEvent當我需要它。 periodicEvent如何暫停和重新啓動?或者有沒有更好的方法來使用培根?

+0

'whenNeeded'是培根流/ propert以及? – Bergi

回答

1
  1. 不純的方式做到這一點是增加一個過濾器變量您訂閱之前檢查,然後修改變量時,你不希望發生的訂閱動作:

    var isOn = true; 
    periodicEvent.filter(() => isOn).onValue(() => { 
         doStuff(); 
    }); 
    
  2. 「純-R」的方式做這將是把一個輸入的真/假的屬性和過濾您根據財產的價值流:

    // make an eventstream of a dom element and map the value to true or false 
    var switch = $('input') 
        .asEventStream('change') 
        .map(function(evt) { 
         return evt.target.value === 'on'; 
        }) 
        .toProperty(true); 
    
    
    var periodEvent = Bacon.interval(1000, {}); 
    
    // filter based on the property b to stop/execute the subscribed function 
    periodEvent.filter(switch).onValue(function(val) { 
        console.log('running ' + val); 
    }); 
    

Here is a jsbin of the above code

使用Bacon.when可能會有更好的/更好用的方法,但我還沒有達到那個水平。 :)

+0

絕對不要做不純的版本,基於屬性的過濾是正確的方法。 – OlliM