The Problem
Because of (Why) below, I need to populate a table of function calls with parameters that are used as callbacks when the user clicks a variable number of UI items in the web page window.
I know of two ways to do it. One works, and is very clumsy, and one doesn't, but would be very clean if it can be made to do so.
What Works
So the following works perfectly, want_details()
variously receives 1 and 2, but this approach is a clunky mess for many functions (I need 50 of them):
window.onload = loadPage
var dy_details_functions = [];
dy_details_functions['cb_itemOptions1'] = function () { want_details(1); }
dy_details_functions['cb_itemOptions2'] = function () { want_details(2); }
...
dy_details_functions['cb_itemOptions50'] = function () { want_details(50); }
What Doesn't Work
While the following approach, much preferred for clarity and brevity and script size, does not work as expected:
window.onload = loadPage
var dy_details_functions = [];
function pop_details()
{
var i;
for (i=1; i<51; i++)
{
dy_details_functions['cb_itemOptions'+String(i)] =
function () { want_details(i); }
}
}
The result of the above is that the functions get created in the table, and they are called properly when I need them to, but all with parameter set to the value of i after the loop is finished.
Also, just as a more general issue, what seems peculiar to me is that i was declared local to the function. If it's being assigned at function execution time to the function call from the global namespace... why is it still 51? I do other things with (supposedly) local "i" variables after this runs but before the functions are called, but it's the 3 in this function that ends up as the parameter for both of these. If I do 1...50, it's 51. If I do 1..41, it's 42. It is definitely the terminating increment value of the local i that ends up as the parameter for all of the functions. Why is that?)
Why I Need This
This is all to resolve the problem that I have been unable to find a way for a callback to receive any knowledge of the DOM item that initiated it. If THAT has a solution, then I wouldn't need some form of the above and much of my coding would be sooooo much easier. :)
More Detail
Comments below talk about an "event handler". When I say callback, the following is what I mean. I am doing this as I dynamically create things to click on under various circumstances...
// oi_detailsN objects already added to page prior to this
// callername is 'cb_itemOptions'
for (i=1; i<51; i++)
{
mycall = callername+String(i);
sname = "oi_details"+String(i);
document.getElementById(sname).onmousedown = dy_details_functions[mycall];
}
The callback is called just fine when the object is clicked, and clumsy form 1, above, results in just what I need to happen. I understand now that form 2 is no good because JS variables declared in functions are not actually local(!)