Always call event handlers with component as "this"
See original GitHub issueQuite new to preact, but one thing struck my immediately. Wouldn’t it be nicer if event handlers were called with the component in question as the thisArg
automatically. Otherwise everybody needs to handle it everywhere with e.g. lambda bindings or explicit bind
calls. E.g. something like
// Suggested code inside preact
const handler = listener.bind(compInstance);
el.addEventListener('someEvent', handler);
Maybe I’m missing something. Thanks for a nice product!
Issue Analytics
- State:
- Created 5 years ago
- Comments:8 (7 by maintainers)
Top Results From Across the Web
Always call event handlers with component as "this" #1147
Quite new to preact, but one thing struck my immediately. Wouldn't it be nicer if event handlers were called with the component in...
Read more >Event handling (overview) - Event reference - MDN Web Docs
Event handler code can be made to run when an event is triggered by assigning it to the target element's corresponding onevent property, ......
Read more >Handling Events :: Eloquent JavaScript
Though we have ignored it so far, event handler functions are passed an argument: the event object. This object holds additional information about...
Read more >Event Listeners in React Components - Pluralsight
You can create an event listener in a React app by using the window. ... Now you just need to call removeEventListener when...
Read more >React Event Handler - Robin Wieruch
In this React tutorial, we will get to know event handlers in React for HTML elements such as button and input elements.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Just a heads up, the value of
this
in event handlers is likely to change in an upcoming major version of Preact. Closing for now since it’ll likely change to the element the handler was bound to (matching how addEventListener works).I think we’re going to see some movement in the component definition space soon - perhaps away from ES Classes once again, to simple factories that handle autobinding for you.
Personally, when I can get away with it, I prefer to use a decorator to declaratively bind methods to my component instances: