Trevor Burnham
Trevor Burnham

Reputation: 77426

Test whether an object is a DOM event

From within a function like:

function eventHandler(e) {
  // ...
}

is there a reliable and efficient way to determine whether e is a DOM event?

Upvotes: 6

Views: 173

Answers (3)

Shmiddty
Shmiddty

Reputation: 13967

I don't believe there is a reliable way to determine if a given object is NOT a DOM event.

  1. typeof e will always return 'object' for genuine Event objects, which is not helpful.
  2. Any property that you might check for on the object can exist in both a genuine Event object or any non-Event object.
  3. You might think that the prototype chain could be of use in determining this, but it has the same problem as #2 (can easily be replicated).
  4. The contructor property might seem promising, but one could do this:
function DummyEvent(){
    this.constructor.toString = function(){
        return "function MouseEvent() { [native code] }";
    }
}

This ends up making console.log(e.constructor) print "function MouseEvent() { [native code] }"

So, is there a "reliable" way to tell if an object is an event? No.

Edit — Note that all of this is irrelevant if you want to prevent event spoofing as you can create real events easily.

var evt = new Event('click');
var evt2 = document.createEvent('MouseEvents');
evt2.initMouseEvent('click', ...);
//etc

Edit2 — I've created a test jsFiddle trying to find some way to distinguish objects, but I haven't found anything definite yet. Note that I didn't bother to specify properties on the DummyEvent because those can obviously easily be spoofed.

Upvotes: 3

AlecTMH
AlecTMH

Reputation: 2755

In jquery I created a testing function, something like this:

function isEvent(e) {
    try { 
        e.PreventDefault();
        return true;
    }
    catch (err) {
        return false;
    }

}

and testing code:

var o = new Object();
var e = $.Event('click');
alert(isEvent(o));
alert(isEvent(e));

the former alert shows false, while the latter shows true. See fiddle.

UPDATE: It's safer to call something like preventDefault instead of trigger.

Upvotes: -1

kidwon
kidwon

Reputation: 4524

Perhaps if the event bubbles event.bubbles up through the DOM it's DOM event. But even if that statement is true its propagation might be stopped.

UPDATED :

OK the property you are looking for is e.target and for IE e.srcElement. Both properties return the HTML element the event took place on which defines it as DOM event.

However perhaps you should specify what you interpret as DOM event. Do you mean browser's native events, because this is DOM event too:

var zoo = jQuery('#zoo');
zoo.bind('moo');
zoo.trigger('moo');

It is binded to a DOM node

Upvotes: 0

Related Questions