Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript obj.onevent=callback vs obj.addEventListener(event,callback)

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 ?

like image 698
sbr Avatar asked Mar 02 '26 22:03

sbr


2 Answers

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/

like image 87
enhzflep Avatar answered Mar 04 '26 12:03

enhzflep


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.

like image 34
user2495105 Avatar answered Mar 04 '26 12:03

user2495105



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!