Hacker News new | ask | show | jobs
by h2s 4907 days ago
The most common gotcha I encounter in Javascript has to do with callbacks. I see this problem all the time in my own code and that of my colleagues: callbacks that have been registered either more or less times than the author of the code expected. Usually more times.

This can manifest itself in many ways. Usually in the form of a UI element being displayed more than once, but often more subtly such as a HTTP request being sent more than once. Often the bugs only manifest themselves after a certain sequence of actions, for example: click this UI element, check this radio box, then hit submit and watch the net tab.

It's so often the root cause of Javascript bugs that if I or somebody else on my team has a Javascript problem, I often start by asking myself if it looks like it could be this. Lately I have begun to wonder if there isn't some slight truth to that inflammatory "Callbacks are the new goto" story that was on here a couple of months ago [1].

[1] http://elm-lang.org/learn/Escape-from-Callback-Hell.elm

2 comments

I see this problem all the time in my own code and that of my colleagues: callbacks that have been registered either more or less times than the author of the code expected. Usually more times.

I've yet to run into this problem before, and I'm an even split between JS / Ruby these days. Are you building on top of any particular libraries or frameworks? Could you give some examples of where you've encountered this?

I've encountered it once with a form, although it was a while ago and if I saw the code again I might be able to identify what was wrong. In that case it was probably a poor choice of element to attach to that caused the callback to be fired independently multiple times on one click, and stopping the bubbling had no effect.

The other time was in a Rails app, where a script was added to a partial for a layout, and then added again later on (by a different developer) to the layout itself. That caused a particularly nasty bug since it used 'toggle', and thus the second callback negated the first.

i've also run into this, usually through double event binding
Multiple registration of callbacks and "too many similar events firing" (and even circular event firing : event A triggers event B, event B triggers event A) can all be solved by using event filtering no!?

I'm not saying it's a good thing to work around the issue by using event filtering, but events filtering is a great technique.

You can also use your event filtering to "fail fast" during development: detect a duplicated event called back? Throw an exception / make your application fail.