JavaScript

Kevin Faust
Kevin Faust
15,344 Points

addEventListener vs things like onclick, onchange, etc. (pure javascript)

addEventListener seems to be the easier way to use onclick,onchange, etc and more closely resembles jquery's '.on' event handler (which i prefer). i was wondering if i can use addEventListener for all my events rather than onclick, onchange, etc. any pros and cons to either?

thanks

4 Answers

akak
akak
29,435 Points

I don't think you can get away without using bind in those situation. But in cases when you don't need to change context of this and want to pass arguments, you can write:

var arg = 5;
element.addEventListener('click', myFunction.bind(null, arg));

Here you don't change a context - just passing a function that will not execute immediately. I don't know if it would count for you as thing making code less readable but I've adopted and using this solution in my own code. :)

Rob Cowper
Rob Cowper
5,352 Points

Thanks, I tried out your suggestion and found it really helpful. The main thing I was trying to keep was being able to have the parameters named and ideally still having access to 'this' in a more normal context and that seems to do the job well, I tried with multiple arguments too and all working :)

Michael Hulet
MOD
Michael Hulet
Treehouse Moderator 46,967 Points

You can use addEventListener as long as what you're listening for broadcasts an event (like a click or change event). In my experience, this is often preferred to assigning to onclick or similar, because you can add multiple listeners, instead of a single onclick function. In fact, though the rabbit hole is deeper than I'm willing to travel right now, I would bet that this is how jQuery handles it under the hood

akak
akak
29,435 Points

When I'm not working in a framework that has it's own way of handling event listeners I tend to use addEventListener exclusively. Apart from, as was mentioned before, ability to assign multiple listeners, also the ease of removeEventListeners in that approach is added benefit. I can clearly see when I add one, when I remove one etc. Of course as long as you don't need IE8 and before compatibility.

Rob Cowper
Rob Cowper
5,352 Points

Hi, I've been getting a in a bit of tangle with a project I'm working on. I was trying to exclusively use addEventListener, but have found I get a bit stuck when I need to pass arguments to the function reference. I did find that I could get around it by using the bind method to send my argument by redefining the functions' 'this' but doing so makes my code a lot less readable so I'm currently using onSomething type event handlers.

Does anyone have any information that would help, or am I making a more fundamental mistake?

Thanks!