In Javascript I have code like:
document.addEventListener("mousedown", mouseDownHandler);
and occasionally I might fat finger something like:
document.addEventListener("mouzedown", mouseDownHandler);
And Javascript won’t recognize that I’m a moron and I’ll be confused why my handler isn’t working.
Actionscript3 specifies event constants like so:
MouseEvent.MOUSE_DOWN // equiv to the String "mouseDown"
If I fat-finger a variable or constant then JS gets mad at me and I can solve the problem real quick. Does JavaScript have anything similar to to this or do I need to make my own JS pseudo-constants for event types?
There is no built-in feature to do this for you.
You could create your own list of events:
But that doesn’t protect you from typos because then
EventNames.MOUZE_DOWNwill just give youundefined(which will likely be accepted byaddEventListener()but – obviously – not do what you want).You could create a series of individual global variables and then the browser should give an error if you make a typo on the “constant” name (and your IDE or lint product may detect typos for you):
But of course members of the “globals are evil” brigade are already starting to froth at the mouth just from having read the above. You could do the above without globals by wrapping all of your code (including those “constants”) in one big immediately-executed anonymous function, or you could instead do something like this:
Of course, the usual caveat about using
Array.indexOf()applies, i.e., not supported in older browsers but you can shim it as described by MDN, blah, blah, blah.Or you could do like jQuery and define your own
.mousedown(),.click()etc methods and only attach events through those methods – you’ll definitely get an error if you mistype the method name.