0

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

Community
  • 1
  • 1
  • You are calling the function and assigning the result, not assigning the function itself. – RobG Jul 02 '14 at 01:22
  • Doing `allCells[i].domInfo.onclick = userFlipsStatusOfCell(i);` will assign the return value of that function into the onclick property. You instead need to assign the function itself. – techfoobar Jul 02 '14 at 01:22
  • Excellent education for me. Thanks everyone. Gonna play with this concept until it sticks. – TheNeophyte Jul 02 '14 at 01:35

1 Answers1

0

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));
RobG
  • 142,382
  • 31
  • 172
  • 209
  • I now have a working "game of life". Thank you. This answer almost verbatim is out there somewhere, it didn't work for me. They didn't use "return", and perhaps that's the difference. If I find that answer again, I'll link it here. – TheNeophyte Jul 02 '14 at 01:37