JavaScript Anonymous Functions Javascript

I am trying to register an anonymous function when a user clicks a cell in an HTML table. Here are some of the raw code:

document.getElementById(
    "course"+displayed_year_index+occurrences_indices[displayed_year_index]).onclick =
        eval("function() {PrintReceipt("+result.years[result_year_index].rul_code+");};");

      

Note the usage eval

as this sits in a loop and the anonymous function is different every time.

Suffice it to say that it works fine in Firefox 2. But Firefox 3 throws a "Syntax error" by putting the word "function" inside the parentheses.

Does anyone have any clever ideas on how I can fix this?


Just to understand what I am trying to do, here's a very simplified example:

for (index=0; index<4; index++) {
    document.getElementById("div"+index).onclick = 
        eval("function () {Foo(index);};");
}

      

In other words, I want to call the same function with a different parameter value for each div

.

+1


source to share


4 answers


Closure IMHO shouldn't be used in this case and there is no need to create a new function for each onlick (uses much more memory than necessary) and eval is not the right answer.

Do you know that the element you get with getElementById is an object and that you can assign values ​​to it?

for ( /* your definition */ ) {
  var e = document.getElementById(
    "course"+displayed_year_index+occurrences_indices[displayed_year_index]
  );
  e.rul_code = result.years[result_year_index].rul_code;
  e.onclick = PrintReceipt;
}

      



But first, you must define a PrintReceipt:

function PrintReceipt() {
  //This function is called as an onclick handler, and "this" is a reference to the element that was clicked.
  if (this.rul_code === undefined) { return; }
  //Do what you want with this.rul_code
  alert (this.rul_code);
}

      

+4


source


Have you tried something like this?

document.getElementById('course' + displayed_year_index + occurences_indices[displayed_year_index]) =
    function (nr)
    {
        return function () { PrintReceipt(nr) }
    } (result.years[result_year_index].rul_code);

      



Could you please post a loop to help us find the problem and not make us guess what you are trying to do?

+5


source


Use closure as Tom suggested.

Here's a good explanation by John Resig: How Jobs Close (pdf)

+1


source


It looks like this is the direction you would like to go:

document.getElementById("course"+displayed_year_index+occurrences_indices[displayed_year_index]).addeventlistener("click",  function() {
    var current_rul_code = result.years[result_year_index].rul_code;
    PrintReceipt(current_rul_code);
}, true);

      

This should result in each onclick event being raised in a different scope (each iteration of the loop). Closures will take care of the rest.

0


source







All Articles