我想修改一个如下所示的库函数:
this.map.getContainer().addEventListener('touchstart', this.fire.bind(map, 'mousedown'));
现在(如果我做对了),该函数侦听触摸事件,如果发生,则调度相应的鼠标事件。因此,它告诉地图对象像处理鼠标事件一样处理触摸事件。
this.map.on('mousedown', this.eventHandlers.mouseDown);
this.eventHandlers = {
mouseDown: this.events.mouseDown.bind(this),
};
我想修改上面的函数,以便区分单指触摸事件和多点触摸事件,如下所示:
element.addEventListener('touchstart', onTouchStart);
function onTouchStart(e) {
if (e.touches.length > 1) { foo() } else { this.fire.bind(map, 'mousedown') }
};
但是,它不适用于仅将上述侦听器函数放在那里。我尝试使用 e.currentTarget 并创建一个 var otherThis = this,然后用 otherThis 替换它,但它不起作用。
我收到以下错误:
未捕获的类型错误:无法读取未定义的属性"绑定" at HTMLDivElement.onTouchStart
非常感谢帮助!
这是 XY 问题的一个实例。
您不需要将触摸事件转换为鼠标事件(touchstart
→mousedown
、touchmove
→mousemove
、touchend
→mouseup
),反之亦然:浏览器已经为您完成了此操作。
我强烈建议您观看 2015 年的"变得敏感"演示文稿以及阅读相应的幻灯片。它深入解释了不同的浏览器如何将鼠标(和指针)事件与触摸事件一起调度。
即使您仅在触摸事件的某些条件下调度mousedown
/up
/move
,您也会收到单个触摸的重复mousedown
/up
/move
事件。
另一方面:在这里绑定事件处理程序的干净方法...
element.addEventListener('touchstart', onTouchStart);
function onTouchStart(e) {
if (e.touches.length > 1) { foo() } else { this.fire.bind(map, 'mousedown') }
};
。将。。。
element.addEventListener('touchstart', onTouchStart.bind(this));
function onTouchStart(e) {
if (e.touches.length > 1) { foo() } else { this.fire('mousedown') }
};
请注意如何将bind()
调用应用于事件处理程序函数,而不是应用于事件处理程序中的函数调用。这使得事件处理程序中的this
值成为bind()
的参数。
"传单方式"将是...
L.DomEvent.on(element, 'touchstart', onTouchStart, this)
。这是bind
和addEventListener
上的几个包装器.L.DomEvent
还处理浏览器怪癖(在某些情况下dblclick
触摸屏上),并翻译非标准IE10的MSPointerDown
(等),以便在具有IE10和触摸屏的Win7计算机上touch*
事件将起作用。
在这里:
function onTouchStart(e) {
if (e.touches.length > 1) { foo() } else { this.fire.bind(map, 'mousedown') }
};
问题this.fire.bind(map, 'mousedown')
。这段代码没有副作用,它只是定义了一个函数。请参阅绑定。但实际上并没有叫它。
要调用它,您可以使用:
this.fire('mousedown');