3

I have a function that might either be called explicitly or when an event fires. If it's triggered by an event, I need to ignore a function parameter that might otherwise have a useful value.

Is there a reliable, cross-browser way I can check whether an object is an event?

We've been using this, but realized it doesn't work in IE7 since Event is undefined:

var view = {
    save: function (data) {
        if (data.constructor === Event.constructor) {
            // It's an event.
        }
    }
};
Brad Koch
  • 17,848
  • 18
  • 106
  • 133

1 Answers1

2

I suppose the "poor man's" way would be to just check for the existence of a certain method that all Event objects have - regardless of how they are created:

if (!(typeof data.altKey == "undefined")) {
  // it's an Event
}

EDIT

Since preventDefault isn't accepted in some versions of IE I've changed the solution to use a different property, really any common property should work just fine.

Jordan Kasper
  • 12,642
  • 3
  • 34
  • 52