简体   繁体   中英

Distinguish JavaScript events

What is the best way to distinguish events in JavaScript.

Actually there are two points I am interested in. The first one is are there something like id in event (it would be very useful foe debugging purposes). And another point are there better ways to distinguish mousedown and mousedown & touchstart events.

Let me tell you my story. I met the problem that if you add two dom events to a node with triggers mousedown and touchstart , then on mobile devices both mousedown and touchstart run.

The first solution I found was to run

event.preventDefault();
event.stopPropagation();

at the beginning of each listener function.

But then I found out an event delegation pattern and started to work with analytics, all that disallowed to use the previous approach, so I come up with the following solution:

let lastEvent = null;
const specificListener = function(e) {
  if (lastEvent === e) {
    return; //already run the code due to another listener
  }

  /*
  logic goes here
  */ 

  lastEvent = e;
};

And now I am interested whether or not it is possible to compare events in a different way (different from event1 === event2, hope to find out about something like event1.id === event2.id)?

Thank you.

Instead of trying to differentiate the events, just subscribe to mousedown only, as it is fired anyway. That's the most simple solution I'd say.

Or, you could try to detect which event system is supported and only subscribe to the appropriate one:

var eventType = document.ontouchstart != null ? 'touchstart' : 'mousedown';

document.addEventListener(eventType, (e) => { ... });

A third solution (possibly) would be to use PointerEvents only, but that depends on the platforms you need to support. https://caniuse.com/#search=pointer%20events

If you for sure cannot use one of these approaches: Every event should have a timestamp property (not sure if it is named that way), maybe you can find a way to distinguish two events with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM