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

发布于 2024-12-25 13:47:09 字数 851 浏览 3 评论 0原文

在处理浏览器事件时,我开始将 Safari 的 touchEvents 合并到移动设备中。我发现 addEventListener 与条件语句堆积在一起。 这个项目不能使用 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 允许多个事件,如下所示:

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

有没有办法将两个事件监听器组合为在 JQuery 示例中? 例如:

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

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

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.

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:

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

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

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

Any suggestions or tips are appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

凉栀 2025-01-01 13:47:09

一些可以实现所需结果的紧凑语法,POJS:

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

Some compact syntax that achieves the desired result, POJS:

   "mousemove touchmove".split(" ").forEach(function(e){
      window.addEventListener(e,mouseMoveHandler,false);
    });
最好是你 2025-01-01 13:47:09

在 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(){…});

希望它能展示这个概念。

编辑 2016-02-25

Dalgard 的评论让我重新审视了这一点。我想现在更常见的是在一个元素上为多个事件添加相同的侦听器,以涵盖正在使用的各种接口类型,并且 Isaac 的答案提供了一种很好的使用内置方法来减少代码的方法(尽管代码本身较少) ,不一定是奖金)。使用 ECMAScript 2015 箭头函数扩展给出:

function addListenerMulti(el, s, fn) {
  s.split(' ').forEach(e => el.addEventListener(e, fn, false));
}

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

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.

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

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.

開玄 2025-01-01 13:47:09

清理 Isaac 的答案:

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

编辑

ES6 辅助函数:

function addMultipleEventListener(element, events, handler) {
  events.forEach(e => element.addEventListener(e, handler))
}

Cleaning up Isaac's answer:

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

EDIT

ES6 helper function:

function addMultipleEventListener(element, events, handler) {
  events.forEach(e => element.addEventListener(e, handler))
}
暮光沉寂 2025-01-01 13:47:09

为我;该代码工作正常,并且是使用相同(内联)函数处理多个事件的最短代码。

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.");
    });
}

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.");
    });
}
雨巷深深 2025-01-01 13:47:09

ES2015:

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

ES2015:

let el = document.getElementById("el");
let handler =()=> console.log("changed");
['change', 'keyup', 'cut'].forEach(event => el.addEventListener(event, handler));
疾风者 2025-01-01 13:47:09

我为您提供了一个更简单的解决方案:

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

我已经对此进行了测试,它效果很好,从好的方面来说,它像这里的其他示例一样紧凑且简单。

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.

緦唸λ蓇 2025-01-01 13:47:09

您还可以使用原型将自定义函数绑定到所有元素

Node.prototype.addEventListeners = function(eventNames, eventFunction){
    for (eventName of eventNames.split(' '))
        this.addEventListener(eventName, eventFunction);
}

然后使用它

document.body.addEventListeners("mousedown touchdown", myFunction)

You can also use prototypes to bind your custom function to all elements

Node.prototype.addEventListeners = function(eventNames, eventFunction){
    for (eventName of eventNames.split(' '))
        this.addEventListener(eventName, eventFunction);
}

Then use it

document.body.addEventListeners("mousedown touchdown", myFunction)
半窗疏影 2025-01-01 13:47:09

一种方法:

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>

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>

浪漫人生路 2025-01-01 13:47:09

AddEventListener 采用一个表示 事件类型。因此,您需要编写一个自定义函数来迭代多个事件。

这是在 jQuery 中通过使用 .split(" ") 进行处理,然后迭代列表以设置每个类型的事件监听器。

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

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

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

    // 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
紫﹏色ふ单纯 2025-01-01 13:47:09

下面是一个小函数,可将此功能注入到 HTMLElement 类中,使其像任何其他元素方法一样可访问:

HTMLElement.prototype.addEventListeners = function addEventListeners(events, handler, ...args) {
    // Allow for easy assignment of one listener to multiple events
    if ((events instanceof Array) && (handler instanceof Function)) {
        events.filter(e=>isString(e)).forEach((evtype) => {
            this.addEventListener(evtype, handler, ...args);
        });
    } else {
        throw new TypeError(`${this.constructor.name}.addEventListeners(): The events must be an Array of Strings and the handler must be a Function! (got events:${events?.constructor?.name||events} and handler:${handler?.constructor?.name||handler})`);
    }
}

此代码注入方法 addEventListeners(events, handler, ...args) 到 HTMLElement 基类中,因此每个 HTML 元素都会获取它。
例如,要让元素在发生事件后打印到控制台,请执行以下操作:

document.getElementById('elmnt-with-many-actions').addEventListeners(
    [
        'click',
        'dblclick',
        'focus',
        'blur'
    ], (event) => {
        console.log('Something happened: %O', event);
    },
    {once:true}
);

Here's a little function that injects this functionality into the HTMLElement class to make it accessible like any other element method:

HTMLElement.prototype.addEventListeners = function addEventListeners(events, handler, ...args) {
    // Allow for easy assignment of one listener to multiple events
    if ((events instanceof Array) && (handler instanceof Function)) {
        events.filter(e=>isString(e)).forEach((evtype) => {
            this.addEventListener(evtype, handler, ...args);
        });
    } else {
        throw new TypeError(`${this.constructor.name}.addEventListeners(): The events must be an Array of Strings and the handler must be a Function! (got events:${events?.constructor?.name||events} and handler:${handler?.constructor?.name||handler})`);
    }
}

This code injects the method addEventListeners(events, handler, ...args) into the base HTMLElement class, so every HTML element will get it.
To e.g. let an element print into the console once what happened to it, do like the following:

document.getElementById('elmnt-with-many-actions').addEventListeners(
    [
        'click',
        'dblclick',
        'focus',
        'blur'
    ], (event) => {
        console.log('Something happened: %O', event);
    },
    {once:true}
);
绮筵 2025-01-01 13:47:09
// BAD: One for each event - Repeat code
textarea.addEventListener('keypress', (event) => callPreview);
textarea.addEventListener('change', (event) => callPreview);

// GOOD: One run for multiple events
"keypress change".split(" ").forEach((eventName) => textarea.addEventListener(eventName, callPreview));

// BAD: One for each event - Repeat code
textarea.addEventListener('keypress', (event) => callPreview);
textarea.addEventListener('change', (event) => callPreview);

// GOOD: One run for multiple events
"keypress change".split(" ").forEach((eventName) => textarea.addEventListener(eventName, callPreview));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文