Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Kevin Faust15,353 Points
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?
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. :)
Michael HuletTreehouse Moderator 47,826 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
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 Cowper5,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?