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.
        }
    }
};
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Brad Koch
  • 19,267
  • 19
  • 110
  • 137

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
  • 13,153
  • 3
  • 36
  • 55