addEventListener in HTML5 development
As an AS3 developer I am used to this:
I am trying to learn Typescript/JS/HTML5 and I keep seeing all these different ways of doing things.
I love this style:
I hate this style:
window.onresize = function();
Can someone explain why these 2 approaches exist? Are they interchangable? If I see window.onfoo on a dom API reference can I use window.addEventListener("onfoo", this.onFoo);
Finally, is there a static event list anywhere in the dom? Can I say Event.onresize or do I need to type the string?
I think you mean:
There is no such thing as an onresize event in modern browsers, but there is an onresize property in the DOM.
Can someone explain why these 2 approaches exist?
The 'inline handlers; exist for historic/backwards compatibility reasons and reflect the attributes that can be added to HTML markup. In the same way you have a click event, an onclick DOM property and an onclick attribute - the pattern repeats for many other events.
Inline event registration has a number of limitations, the most obvious being you can only have a single property/attribute per element. Netscape and Microsoft developed more advanced (but incompatible) models and the W3C then attempted to standardize in the DOM Level 2 spec which all modern browsers implement.
However IE continued to use Microsoft's proprietary model until version 9, and this is perhaps what confused your first example:
Are they interchangable?
If you add both an inline event handler and attach one with addEventListener then, providing you don't purposely cancel the event, both handlers will run (that is - they're not the same thing). However, in order to prevent future insanity, I recommend sticking with the more modern approach.
Finally, is there a static event list anywhere in the dom?
No, there's not even a universal list in any one standard, because the events themselves tend to be defined in specs where they're relevant rather than alongside the definition of the mechanism. You might want to define a function like isEventSupported() or use Modernizr if you are concerned about browser support for particular events.