Search code examples
javascriptjqueryeventsdom-eventsv8

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 ?


Solution

  • 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/