将多个事件绑定到侦听器(没有JQuery)?

时间:2021-03-12 00:05:20

While working with browser events, I've started incorporating Safari's touchEvents for mobile devices. I find that addEventListeners are stacking up with conditionals. This project can't use JQuery.

在处理浏览器事件时,我已经开始为移动设备集成Safari的touchEvents。我发现addeventlistener中充斥着条件语句。这个项目不能使用JQuery。

A standard event listener:

一个标准的事件监听器:

/* 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's bind allows multiple events, like so:

JQuery的绑定允许多个事件,如下所示:

$(window).bind('mousemove touchmove', function(e) {
    //do something;
});

Is there a way to combine the two event listeners as in the JQuery example? ex:

是否有一种方法可以像JQuery示例那样组合这两个事件监听器?例:

window.addEventListener('mousemove touchmove', this.mouseMoveHandler, false);

Any suggestions or tips are appreciated!

如有任何建议或建议,我们将不胜感激!

8 个解决方案

#1


72  

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.:

在POJS中,每次添加一个侦听器。在同一个元素上为两个不同的事件添加相同的侦听器并不常见。你可以自己写一个小函数来完成这项工作,例如:

/* 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.

希望它能展示这个概念。

Edit 2016-02-25

编辑2016-02-25

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:

达尔加德的评论让我重新审视这一点。我猜想,在一个元素上为多个事件添加相同的监听器现在更常见,以覆盖使用的各种接口类型,Isaac的答案很好地利用了内置的方法来减少代码(尽管代码本身较少,不一定是额外的)。扩展ECMAScript 2015 arrow功能,给出:

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.

类似的策略可以将相同的侦听器添加到多个元素中,但这样做的需要可能是事件委托的指示符。

#2


82  

Some compact syntax that achieves the desired result, POJS:

一些紧凑的语法实现了预期的结果,POJS:

   "mousemove touchmove".split(" ").forEach(function(e){
      window.addEventListener(e,mouseMoveHandler,false);
    });

#3


19  

Cleaning up Isaac's answer:

清理艾萨克的回答:

['mousemove', 'touchmove'].forEach(function(e) {
  window.addEventListener(e, mouseMoveHandler);
});

#4


9  

ES2015:

ES2015:

let el = document.getElementById("el");
let handler =()=> console.log("changed");
['change', 'keyup', 'cut'].forEach(event => el.addEventListener(event, handler));

#5


7  

For me; this code works fine and is the shortest code to handle multiple events with same (inline) functions.

对我来说;这段代码运行良好,是处理具有相同(内联)函数的多个事件的最短代码。

var eventList = ["change", "keyup", "paste", "input", "propertychange", "..."];
for(event of eventList) {
    element.addEventListener(event, function() {
        // your function body...
        console.log("you inserted things by paste or typing etc.");
    });
}

#6


3  

I have a simpler solution for you:

我有一个更简单的解决方法:

window.onload = window.onresize = (event) => {
    //Your Code Here
}

I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.

我已经测试过它的效果很好,从好的方面来说它是紧凑的和简单的就像这里的其他例子一样。

#7


1  

AddEventListener take a simple string that represents event.type. So You need to write a custom function to iterate over multiple events.

AddEventListener使用一个简单的表示事件的字符串。因此,您需要编写一个自定义函数来迭代多个事件。

This is being handled in jQuery by using .split(" ") and then iterating over the list to set the eventListeners for each types.

这是通过使用.split(")来处理的,然后遍历列表以设置每个类型的eventlistener。

    // Add elem as a property of the handle function
    // This is to prevent a memory leak with non-native events in IE.
    eventHandle.elem = elem;

    // Handle multiple events separated by a space
    // jQuery(...).bind("mouseover mouseout", fn);
    types = types.split(" ");  

    var type, i = 0, namespaces;

    while ( (type = types[ i++ ]) ) {  <-- iterates thru 1 by 1

#8


0  

One way how to do it:

一种方法是:

const troll = document.getElementById('troll');

['mousedown', 'mouseup'].forEach(type => {
	if (type === 'mousedown') {
		troll.addEventListener(type, () => console.log('Mouse is down'));
	}
        else if (type === 'mouseup') {
                troll.addEventListener(type, () => console.log('Mouse is up'));
        }
});
img {
  width: 100px;
  cursor: pointer;
}
<div id="troll">
  <img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>

#1


72  

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.:

在POJS中,每次添加一个侦听器。在同一个元素上为两个不同的事件添加相同的侦听器并不常见。你可以自己写一个小函数来完成这项工作,例如:

/* 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.

希望它能展示这个概念。

Edit 2016-02-25

编辑2016-02-25

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:

达尔加德的评论让我重新审视这一点。我猜想,在一个元素上为多个事件添加相同的监听器现在更常见,以覆盖使用的各种接口类型,Isaac的答案很好地利用了内置的方法来减少代码(尽管代码本身较少,不一定是额外的)。扩展ECMAScript 2015 arrow功能,给出:

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.

类似的策略可以将相同的侦听器添加到多个元素中,但这样做的需要可能是事件委托的指示符。

#2


82  

Some compact syntax that achieves the desired result, POJS:

一些紧凑的语法实现了预期的结果,POJS:

   "mousemove touchmove".split(" ").forEach(function(e){
      window.addEventListener(e,mouseMoveHandler,false);
    });

#3


19  

Cleaning up Isaac's answer:

清理艾萨克的回答:

['mousemove', 'touchmove'].forEach(function(e) {
  window.addEventListener(e, mouseMoveHandler);
});

#4


9  

ES2015:

ES2015:

let el = document.getElementById("el");
let handler =()=> console.log("changed");
['change', 'keyup', 'cut'].forEach(event => el.addEventListener(event, handler));

#5


7  

For me; this code works fine and is the shortest code to handle multiple events with same (inline) functions.

对我来说;这段代码运行良好,是处理具有相同(内联)函数的多个事件的最短代码。

var eventList = ["change", "keyup", "paste", "input", "propertychange", "..."];
for(event of eventList) {
    element.addEventListener(event, function() {
        // your function body...
        console.log("you inserted things by paste or typing etc.");
    });
}

#6


3  

I have a simpler solution for you:

我有一个更简单的解决方法:

window.onload = window.onresize = (event) => {
    //Your Code Here
}

I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.

我已经测试过它的效果很好,从好的方面来说它是紧凑的和简单的就像这里的其他例子一样。

#7


1  

AddEventListener take a simple string that represents event.type. So You need to write a custom function to iterate over multiple events.

AddEventListener使用一个简单的表示事件的字符串。因此,您需要编写一个自定义函数来迭代多个事件。

This is being handled in jQuery by using .split(" ") and then iterating over the list to set the eventListeners for each types.

这是通过使用.split(")来处理的,然后遍历列表以设置每个类型的eventlistener。

    // Add elem as a property of the handle function
    // This is to prevent a memory leak with non-native events in IE.
    eventHandle.elem = elem;

    // Handle multiple events separated by a space
    // jQuery(...).bind("mouseover mouseout", fn);
    types = types.split(" ");  

    var type, i = 0, namespaces;

    while ( (type = types[ i++ ]) ) {  <-- iterates thru 1 by 1

#8


0  

One way how to do it:

一种方法是:

const troll = document.getElementById('troll');

['mousedown', 'mouseup'].forEach(type => {
	if (type === 'mousedown') {
		troll.addEventListener(type, () => console.log('Mouse is down'));
	}
        else if (type === 'mouseup') {
                troll.addEventListener(type, () => console.log('Mouse is up'));
        }
});
img {
  width: 100px;
  cursor: pointer;
}
<div id="troll">
  <img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>