Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if Javascript object is an event?

What is the safest way to determine if a Javascript object is an event?

like image 732
Tom Avatar asked Sep 22 '09 08:09

Tom


People also ask

Is event a JavaScript object?

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.

How do you know if an event is an event on the keyboard?

if (e instanceof KeyboardEvent){ // it is a keyboard event! }

What creates the event object in JavaScript?

Constructor. Creates an Event object, returning it to the caller.


2 Answers

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.

like image 23
Felix Avatar answered Sep 22 '22 12:09

Felix


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(...) } 
like image 189
Paul Dixon Avatar answered Sep 20 '22 12:09

Paul Dixon