3 ms·
Attaching an event handler to a dom node is the /only/ way to handle events. As for where to put the setTimeout variable, I would say best practice is just use
by TheZenPsycho 13y ago
Attaching an event handler to a dom node is the /only/ way to handle events. As for where to put the setTimeout variable, I would say best practice is just use underscore's debounce function, and you avoid the question of where to store that variable altogether. (it's kept inside the closure of a wrapped function. secretly. But you don't really care where it is since all we are interested in is the external observable behaviour of the debounced function)
On a broader level, an interesting question is: when is it good practice to attach a variable to a DOM node? I would say very rarely except perhaps in the case where what you are doing is assembling some kind of interface widget out of HTML elements. Then storing information about the widget's state with the dom node is what makes the most sense.
Since in the question, the task at hand is constructing an autocomplete widget, apparently from scratch without recourse to the many easily available robust and tested existing libraries, it does indeed make some sense to store the timeout state with the DOM node. If your goal is a robust reusable component, you want something that can cope with having many instances on a page. to do that and maintain the behavior of one on its own, you can either attach the state with the dom node, or create a framework that simulates doing that, but implements it in some other overly clever way.
- drewblaisdell 13y agoApologies for the ambiguous wording: I meant attaching the timeout ID specifically to the DOM node. dmbass posted a solution above that handles all style issues I had with the answer in the post.
- TheZenPsycho 13y agoyes I see. I suppose it's javascript's version of private instance properties, versus public properties. The timeout ID doesn't need to be public, and probably shouldn't be since what you actually want is an encapsulated self contained widget. You don't really want to have to reach inside of it to touch some implementation detail. So hiding it in a closure takes care of that. If you want the widget to have the capability of cancelling, you should add a cancel method to it.