Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor - for loop index value as onclick parameter not working as expected, creating new variable in each iteration is required. Why?

$
0
0

I am creating a simple tetris game using Blazor WASM. The purpose of the following code is to render a grid of pixels as a game board and send a ROW and COL values as parameters to a function in a onclick event to log which "pixel" has been clicked.

Can someone explain me why this code does not work: (it sends the same (last) value of row and col when clicking on any "pixel")

<div class="board">    @for (int row = 0; row < _height; row++)    {        for (int col = 0; col < _width; col++)        {<div class="pixel" data-row="@row" data-col="@col" @onclick="@(() =>                       LogClickedPixel($"Clicked pixel {row} - {col}"))"></div>        }    }</div>

While this code works? (sends the row and col of the clicked "pixel")

<div class="board">    @for (int row = 0; row < _height; row++)    {        for (int col = 0; col < _width; col++)        {            //assignement to a new variable is required            int _row = row;            int _col = col;<div class="pixel" data-row="@row" data-col="@col" @onclick="@(() =>                  LogClickedPixel($"Clicked pixel {_row} - {_col}"))"></div>        }    }</div>

I want to understand why Blazor needs the variables to be reassigned to new ones. Arent they also temporary living in a scope of the single for loop iteration?

I want to understand why the reassignment is required for Blazor


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>