2016-07-27 51 views
0

每次有人將鼠標懸停在某個按鈕上時,我都能夠登錄到控制檯,但是如何才能確定發生這種事情的時間和聚合總量?RxJS計算在按鈕上停留的時間長度

var result = document.getElementById('result'); 
var source = Rx.Observable.fromEvent(result, 'mouseover'); 
var subscription = source.subscribe(
    function (x) { 
    console.log('Hovered!'); 
    } 
); 

回答

1

如果我理解正確你的要求,你需要檢查時,鼠標也離開元素爲好,然後使用和運營商像scan總結總量。一個相對簡單的方式做,這將是獲得mouseover的時間戳,然後品嚐的mouseout事件:

var result = document.getElementById('result'); 
var mouseOver = Rx.Observable.fromEvent(result, 'mouseover'); 
var mouseOut = Rx.Observable.fromEvent(result, 'mouseout'); 

mouseOver 
    //Get the time of the mouseover event 
    .timestamp() 
    //Don't emit until the mouseOut triggers 
    .sample(mouseOut) 
    //Extract only the timestamp value 
    .pluck('timestamp') 
    //Get a new timestamp (remember this is *after* mouse out) 
    .timestamp() 
    //Compute the timeinterval 
    .map(x => x.timestamp - x.value) 
//Add the new time interval to the running total 
.scan((total, diff) => total += diff, 0) 
.subscribe(x => console.log(x)); 
+0

這個答案非常有幫助謝謝! – Rob

0

這是我想出了,對於技術不是最佳的,但值得分享的一個替代的解決方案。

var counter = 0; 

var source = Rx.Observable.interval(100) 
    .map(() => '.'); 

var display = document.querySelector("#display"); 
var toggle = document.querySelector("#toggle"); 

var hover = false; 

var mouseOver = Rx.Observable.fromEvent(toggle, "mouseenter") 
    .map(e => {hover=true;}); 
var mouseOut = Rx.Observable.fromEvent(toggle, "mouseleave") 
    .map(e => {hover=false;}); 

mouseOver //.filter(x => true) 
    .flatMapLatest(() => source.takeUntil(mouseOut)) 
    .subscribe(x => {counter += 1; display.innerText = counter});