What is the safest way to determine if a Javascript object is an event?
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(...)
}
you can use getAttribute of an object (event) to check whether the object is an event or just an object.
try{
event.getAttribute('type')
isEvent=true;
}
catch(ex)
{
isEvent=false;
}
or if you have the event.type constants then you can loop over them and check whether ihe instance is a event or not
EventNames = new Array();
EventNames[0]="load"; //all event names are kept in this array
for(i=0;i<EventNames;i++)
{
if (event.type==EventNames[i])
isEvent=true;
}
EDIT
cant we just check
try{
if (event.type=="")
isEvent=false;
}
catch(ex)
{
isEvent=false;
}
am sure all events must come with an valid event type.. i think this should work...
Cheers
Ramesh Vel
I don't know if there's a sure-fire way to do that, but I think your best shot is duck-typing.
Anyway, depending on the situation you could check if a given object has the expected properties that you want to use, just like Paul pointed out.