Possible Duplicate:
Access outside variable in loop from Javascript closure
I would like to add to my rails applications keyboard shortcuts, so that pressing e.g. CTRL-N
will result in visiting the notices page (whatever that is). This works well with one shortcut per page only, but not with many shortcuts on one page.
I have done the following:
Add to special elements like links shortcuts. I have added a helper, so that
link_to_shortcut_name
results in HTML code like<a href="/notices" class="current shortcut" data-path="/notices" data-shortcut="ctrl+n" title="Notice (ctrl+n)">Notice</a>
I want to interpret the data then in javascript. For that purpose, I have added to
application.js
the following code:function _mapShortcuts() { var elements = document.getElementsByClassName("shortcut"); for (var i = 0; i < elements.length; i++) { var ele = elements[i]; var sc = ele.getAttribute('data-shortcut'); var path = ele.getAttribute('data-path'); shortcut.add(sc, function(){ window.location = path; }) } } $(function() { _mapShortcuts() });
My expectation was that by adding to different shortcuts different paths to visit, by pressing the shortcut, every time the last path will be visited. It seems that my naive implementation binds all the time inside the anonymous function the path of the last element.
How should I write that function, so that for different keyboard shortcuts, different paths will be bound? I have tried out 3 different implementations, and all of them behave the same, so the fault should be mine.
PS: And what book should I read to avoid such questions in the future?