当mousemove停止时,观察者检查

时间:2016-11-09 07:35:48

标签: javascript observers

我想在mouseDown Observer内鼠标移动结束时执行函数。但当我放弃鼠标时,onComplete函数不会执行。有什么建议吗?

var split = $('.drag');
var parent = $('.Container');

var mouseDowns = Rx.Observable.fromEvent(split, "mousedown");
var parentMouseMoves = Rx.Observable.fromEvent(parent, "mousemove");
var parentMouseUps = Rx.Observable.fromEvent(parent, "mouseup");

var drags = mouseDowns.flatMap(function(e){
   return parentMouseMoves.takeUntil(parentMouseUps);
});

drags.subscribe(
   function(e) {
     var $containerWidth = $('.Container').width();
     var clientX = $containerWidth - e.clientX;

     if (clientX >= 50 && e.clientX >= 50) {
        $('.left').css('right', clientX);
        $('.right').css('width', clientX);
      }
    },
    function(error) {
        console.log(error);
    },
    function() {
        console.log('finished');
    });

jsbin.com url

1 个答案:

答案 0 :(得分:1)

If you want to detect drag event end, a.k.a. drop, then something like this should do the trick:

var drop = mouseDowns.selectMany(
  Rx.Observable.concat([
    parentMouseMoves.take(1).ignoreElements(),
    parentMouseUps.take(1)
  ])
);

drop.subscribe(function(e) {
  console.log('finished');
});

If the outer-most function is suppose to return a value each time a drag completes, you need to convert the drag completion into an "onNext" event for the outer-most observable.