Code
const enterTable = function (data) {
console.log("outside onFill table ID: ", data.TableID);
const onFill = function (x, y) {
console.log("inside onFill table ID: ", data.TableID);
websocketWrite("play", { TableID: String(data.TableID), Row: Number(x), Col: Number(y) });
}
window.game = new Dooz(data.Rows, data.Cols, data.PlayerID, "#game-container", onFill);
showTab(tabs.game);
websocketWrite("enterTable", { TableID: String(data.TableID) });
setInGame(true);
};
The problem with this code is when enterTable
is called more than once, the data.TableID
inside onFill
is different with data.TableID
outside onFill
.
Outputs
When the page is clean (eg. after refresh):
outside onFill table ID: 1611740605479726000
inside onFill table ID: 1611740605479726000
Leave the table and enter again (enterTable
called again):
outside onFill table ID: 1611740615739111000
inside onFill table ID: 1611740605479726000
// Next time onFill is called, it get's updated.
inside onFill table ID: 1611740615739111000
The onFill
function is bound to a click event, the first time on a clean page it's all ok. When enterTable
called for the second time, the data.TableID
in onFill
still holds the previous value, until onFill
get's called again. Why? There are not any async operations in between. I'm using Webpack for bundling.
I've tried These
const onFill = (function (data) {
return function (x, y) {
console.log("inside onFill table ID: ", data.TableID);
websocketWrite("play", { TableID: String(data.TableID), Row: Number(x), Col: Number(y) });
};
})(data);
And
window.game = new Dooz(data.Rows, data.Cols, data.PlayerID, "#game-container", null);
window.game.onFill = function (x, y) {
console.log("inside onFill table ID: ", data.TableID);
websocketWrite("play", { TableID: String(data.TableID), Row: Number(x), Col: Number(y) });
};
And changing const onFill
to let onFill
. But non of the above worked.
question from:
https://stackoverflow.com/questions/65917115/variable-doesnt-update-first-time-in-nested-function