我有一个AngularJS组件,它应该对单击或拖动做出反应(调整区域大小).
我开始在我的应用程序中使用RxJS(ReactiveX),因此我尝试使用它找到解决方案.请求的Angular方面是次要的……
为了简化问题(并训练自己),我根据rx.angular.js拖拽示例制作了一个滑块指令:http://plnkr.co/edit/UqdyB2
请参阅Slide.js文件(其他代码用于其他实验).这个逻辑的代码是:
function(scope, element, attributes)
{
var thumb = element.children(0);
var sliderPosition = element[0].getBoundingClientRect().left;
var sliderWidth = element[0].getBoundingClientRect().width;
var thumbPosition = thumb[0].getBoundingClientRect().left;
var thumbWidth = thumb[0].getBoundingClientRect().width;
// Based on drag'n'drop example of rx-angular.js
// Get the three major events
var mousedown = rx.Observable.fromEvent(thumb, 'mousedown');
var mousemove = rx.Observable.fromEvent(element, 'mousemove');
var mouseup = rx.Observable.fromEvent($document, 'mouseup');
// I would like to be able to detect a single click vs. click and drag.
// I would say if we get mouseup shortly after mousedown, it is a single click;
// mousedown.delay(200).takeUntil(mouseup)
// .subscribe(function() { console.log('Simple click'); }, undefined, function() { console.log('Simple click completed'); });
var locatedMouseDown = mousedown.map(function (event)
{
event.preventDefault();
// console.log('Click', event.clientX - sliderPosition);
// calculate offsets when mouse down
var initialThumbPosition = thumb[0].getBoundingClientRect().left - sliderPosition;
return { from: initialThumbPosition, offset: event.clientX - sliderPosition };
});
// Combine mouse down with mouse move until mouse up
var mousedrag = locatedMouseDown.flatMap(function (clickInfo)
{
return mousemove.map(function (event)
{
var move = event.clientX - sliderPosition - clickInfo.offset;
// console.log('Move', clickInfo);
// calculate offsets from mouse down to mouse moves
return clickInfo.from + move;
}).takeUntil(mouseup);
});
mousedrag
.map(function (position)
{
if (position < 0)
return 0;
if (position > sliderWidth - thumbWidth)
return sliderWidth - thumbWidth;
return position;
})
.subscribe(function (position)
{
// console.log('Drag', position);
// Update position
thumb.css({ left: position + 'px' });
});
}
这主要是D’n’D水平约束到给定范围.
现在,我想听mousedown,如果鼠标在短时间内发生(例如200 ms,调整),我将其视为点击并进行特定处理(例如,将位置重置为零).
我尝试了延迟().takeUntil(mouseup),如另一个SO答案所示,没有成功.也许也可能需要switch()(以避免拖动路径).
任何的想法?提前致谢.
解决方法:
您可以使用超时(如果您使用ReactiveX / RxJS,则为timeout)
var click$= mousedown.flatMap(function (md) {
return mouseup.timeoutWith(200, Observable.empty());
});
如果在超时之前没有发生mouseup,它只会传播一个空的Observable.如果确实如此,那么下游观察者将收到一个事件.