What is the safest way to determine if a Javascript object is an event?
When a W3C event listener's event occurs and it calls its associated function, it also passes a single argument to the function—a reference to the event object. The event object contains a number of properties that describe the event that occurred.
if (e instanceof KeyboardEvent){ // it is a keyboard event! }
Constructor. Creates an Event object, returning it to the caller.
How about using instanceof
? As long as the event object was created using the constructor new Event()
, for instance:
var e = new Event('click'); e instanceof Event; // true
In case of the event parameter in event handlers, although its type is Object, it contains the native event as a property, so this could be used instead:
function myEventHandler(e) { e.originalEvent instanceof Event; //true }
Here it should be noted that the actual value may vary depending on the browser, specially when the event is a touch event, see here and references within. Not an issue in my case.
It's fairly good practice to probe possibly "unknown" objects for the properties and methods you expect to find.
So, assume you have got an event object, and probe it before acting on it, e.g.
if (event.target) { //looks like we're an event, hide the target var e=$(event.target); e.hide(); }
It's important to note that I'm NOT suggesting you test for 'target' to see if its an event: you're testing for target because you're about to use that property. What I'm driving at is that instead of trying to figure out whether an object is event, probe the object to see whether it is going to behave in the way you expect, then use those behaviours.
Code like this should degrade gracefully on browsers with different support, or let you take advantage of browser-specific extensions, e.g.
if (event.initKeyEvent) { //gecko 1.9+ event.initKeyEvent(...) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With