Ray
Ray

Reputation: 13

Refactoring callback function

I struggle with refactoring my code for a color switch. Color ends up being undefined.

How can I pass the color variable from the main module to the modules while passing the callback at the same time?

main.js

import { changeColor } from "./changeColor.js"
import { showColor } from "./showColor.js"

let color = "green"

document.getElementById("button").addEventListener("click",() => { changeColor(showColor) })

changeColor.js

function changeColor(callback) {
    if (color === "green") {
        color = "red"
    }
    else {
        color = "green"
    }
    callback()
}

export { changeColor };

showColor.js

function showColor() {
    console.log(color);
}

export { showColor };

Upvotes: 1

Views: 116

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337656

Send the color value as an argument to the function you define as the callback reference, then add the argument to the function definition:

let color = "green";

document.getElementById("button").addEventListener("click", () => {
  changeColor(showColor);
})

function changeColor(callback) {
  color = color === 'green' ? 'red' : 'green';
  callback(color)
}

function showColor(c) {
  console.log(c);
}
<button id="button">Toggle</button>

Upvotes: 1

Related Questions