将多个事件绑定到侦听器(没有JQuery)? [英] Binding multiple events to a listener (without JQuery)?
问题描述
在处理浏览器事件时,我已经开始将Safari的touchEvents用于移动设备。我发现 addEventListener
正在堆积条件。 此项目无法使用JQuery。
While working with browser events, I've started incorporating Safari's touchEvents for mobile devices. I find that addEventListener
s are stacking up with conditionals. This project can't use JQuery.
标准事件监听器:
/* option 1 */
window.addEventListener('mousemove', this.mouseMoveHandler, false);
window.addEventListener('touchmove', this.mouseMoveHandler, false);
/* option 2, only enables the required event */
var isTouchEnabled = window.Touch || false;
window.addEventListener(isTouchEnabled ? 'touchmove' : 'mousemove', this.mouseMoveHandler, false);
JQuery的 bind
允许多个事件,如此:
JQuery's bind
allows multiple events, like so:
$(window).bind('mousemove touchmove', function(e) {
//do something;
});
有没有办法像JQuery示例中那样组合两个事件监听器? ex:
window.addEventListener('mousemove touchmove', this.mouseMoveHandler, false);
任何建议或提示均表示赞赏!
Any suggestions or tips are appreciated!
推荐答案
在POJS中,您一次添加一个侦听器。在同一元素上为两个不同的事件添加相同的侦听器是不常见的。您可以编写自己的小函数来完成这项工作,例如:
In POJS, you add one listener at a time. It is not common to add the same listener for two different events on the same element. You could write your own small function to do the job, e.g.:
/* Add one or more listeners to an element
** @param {DOMElement} element - DOM element to add listeners to
** @param {string} eventNames - space separated list of event names, e.g. 'click change'
** @param {Function} listener - function to attach for each event as a listener
*/
function addListenerMulti(element, eventNames, listener) {
var events = eventNames.split(' ');
for (var i=0, iLen=events.length; i<iLen; i++) {
element.addEventListener(events[i], listener, false);
}
}
addListenerMulti(window, 'mousemove touchmove', function(){…});
希望它显示出这个概念。
Hopefully it shows the concept.
编辑2016-02-25
Dalgard的评论让我重温这个。我想在一个元素上为多个事件添加相同的侦听器现在更常见,以涵盖所使用的各种接口类型,而Isaac的答案提供了很好的内置方法来减少代码(尽管代码本身就少了) ,不一定是奖金)。使用ECMAScript 2015扩展箭头函数给出:
Dalgard's comment caused me to revisit this. I guess adding the same listener for multiple events on the one element is more common now to cover the various interface types in use, and Isaac's answer offers a good use of built–in methods to reduce the code (though less code is, of itself, not necessarily a bonus). Extended with ECMAScript 2015 arrow functions gives:
function addListenerMulti(el, s, fn) {
s.split(' ').forEach(e => el.addEventListener(e, fn, false));
}
类似的策略可以为多个元素添加相同的侦听器,但是需要这可能是事件委托的指标。
A similar strategy could add the same listener to multiple elements, but the need to do that might be an indicator for event delegation.
这篇关于将多个事件绑定到侦听器(没有JQuery)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!