Connect with:
About Me
Alessandro Annini
I'm a freelance developer currently working at I really love framework and its amazing potential and if you're like me, and you want the web to win, please share some snippet of code for the community and grow faster with us
Meta Code | Be careful when using .on(‘keydown’, callback);

Be careful when using .on(‘keydown’, callback);

01 Jul Be careful when using .on(‘keydown’, callback);

In the IRC it has arisen a few times about people with issues with the surface.on() event. I am just writing a quick post to let you know what is happening, and how to avoid it (albeit with rather messy code!).

What happens is people are using the .on(‘keydown’, callback); to trigger an event once, but that isn’t how it works. What happens is the engine checks if there is a keydown trigger every tick, and then executes the callback if there is, which can be rather messy and cause event spam. To avoid this, you simply wrap the method of the callback in a boolean controller, to avoid the engine spamming the callback method. My code is messy, but you should be able to see the difference in the two fiddles below.

In this fiddle, when you hold down enter, the counter increases:


In this fiddle however, you will see how it only increases when the enter button is pressed (not held!).


A developer in nearform, ireland. Making a good user experience in is my goal.

More Posts - Website

Follow Me: