Skip to content
Advertisement

Can I use function generator as event handler?

I have a list of HTMLCollection:

JavaScript

And I have a script of JS:

JavaScript

My goal is to write a keyboardEvent based on .addEventListener("keydown", generatorFunction) method whereby event handler would be presented as function generator i.e. generatorFunction presented above. Is it good or bad practice?

Advertisement

Answer

Using a generator function directly as an event callback wouldn’t make any sense because calling the function wouldn’t execute its body, it would generate and return (to nowhere) an iterator.

Instead you’d need to wrap it in another function which talks to the iterator. I’m not sure exactly what your particular use case is (you talk about keydown events, but don’t say on what element). But here’s a general setup – in this example I’m yielding a number from an array on each keypress. On the final number, done is set to true.

JavaScript

Fiddle

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement