0

As an AS3 developer I am used to this:

addEventListener(Event.RESIZE, onResize);

I am trying to learn Typescript/JS/HTML5 and I keep seeing all these different ways of doing things.

I love this style:

window.addEventListener("resize", this.onResize);

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?

Clark
  • 2,598
  • 3
  • 27
  • 41

1 Answers1

2

I think you mean:

window.addEventListener("resize", this.onResize);

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.

These inline event handlers were what was implemented in Netscape 2.0 when JavaScript first appeared on the scene. They've hung around ever since because the model is straightforward, easy to understand and easy to copy and paste, plus no-one ever made a web browser popular by breaking existing web content, but if you're a professional web developer you shouldn't ever be using them.

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:

window.attachEvent('onresize',this.onResize);

This fundamental incompatibility in event handling between major browsers was one of the main factors (along with XHR) which drove the creation of many of the JavaScript frameworks such as jQuery.

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.

robertc
  • 74,533
  • 18
  • 193
  • 177