3

Does anyone think there is any difference between these two approaches or if either one is better.

Say we have,

var x = new Worker('math.js');
  1. One way of binding the event handler

    x.onmessage = function(ev){ //.... };

  2. Another way of doing it:

    x.addEventListener('message',function(){});

I know one difference is that if we were to have multiple event listeners, addEventListener will be useful. But is there any reason other than that ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
sbr
  • 4,735
  • 5
  • 43
  • 49

2 Answers2

1

Another reason to do it is so that you can remove the event handlers too. If the eventHandler function isn't anonymous (as both of your examples are) then you can remove it by name later.

See here: http://jsfiddle.net/Cs3vL/

enhzflep
  • 12,927
  • 2
  • 32
  • 51
  • It seems the only advantage is the ability to add/remove event listeners – sbr Oct 12 '12 at 17:12
  • Yeah, that and the ability to as you said - add multiple event handlers to a single element. x.onmessage = ... Will always mean that it (x) has a single handler for onmessage, while repeated calling of x.addEventListener will leave each of the handlers attached. :) – enhzflep Oct 12 '12 at 17:19
1

Another thing: With "true" and "false" arguments you can attach to the event in the capturing or bubbling phase. With .onmessage you don't have that choice.