1

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 };

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Rory! Where exactly do you send the color value in your code? Shouldn't it be somewhere in the EventListener part since the color is defined in the main.js?
I understand how the color is handed over from the changeColor.js to showColor.js but how do I send it from main.js to changeColor.js?
If you want to do that I'd suggest storing the color state as a data attribute on the DOM Element which you can read in both scopes, without having to pass any arguments. Alternatively, depending on what you do with the color variable, you could just toggle() a class on the element to update its UI instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.