Search code examples
javascriptarraysfunctionobject-literal

JS: Feeding indexes of an array into their own onclick functions


I'm a tyro. I've hunted around and found answers to similar questions, but implementing their solutions (probably incorrectly) I haven't continuously failed at this. I making my own "Conrad's Game of Life." I have cells that are placed into an array "allCells", of size "worldSize" (which is a variable determined by the user before commencing the "game").

These cells are all Object Literals with various attributes, one of which is their "domInfo", which equals a "div" with a given class name.

I assign the cells all of their properties in a for loop. In that for loop, I want something that functions like this (seems it ought to):

    allCells[i].domInfo.onclick = userFlipsStatusOfCell(i);

userFlipsStatusOfCell is a function that checks the status of the cell (dead or alive) and flips it. It requires the index of the cell in the array.

Secondary question: would changing the cells to a Cell Class and creating a prototype function solve this somehow?

EDIT: pseudo-duplicate (this similar solution lacking the "return" didn't work for me when I tried it), also other good information available here: Get index of clicked element using pure javascript


Solution

  • You are calling the function and assigning the result, not assigning the function. You might be tempted to do:

    allCells[i].domInfo.onclick = function(){userFlipsStatusOfCell(i)};
    

    however that will keep i in a closure so all the listeners will get the same value (the last value that i was set to before exiting the loop). To prevent that, one option is:

    allCells[i].domInfo.onclick = (function(n) {
                                     return function(){userFlipsStatusOfCell(n)};
                                  }(i));