Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - Variable Doesn't Update First Time in Nested Function

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...