As a part of the same voting mechanism that I wrote about for this article on event handler parameter passing, I wanted to keep id and (vote) direction around for the callback, which was to update the UI.
First, I made an ajax call with jquery to make vote updates to the database, and on my way to the ajax call, I would save the id and direction in a global (bad) variable. This works, because later, I can reference it in my callback function, updateUI:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
The next solution is a bit cleaner and makes us feel better about ourself. Instead of the global, a closure is used, in which we decorate the response object with new state (id and direction); and since the response object is passed by default into the ajax callback function, it’s available later by calling response.id or response.objectid:
1 2 3 4 5 6 7 8 9 10 11 12 13 14