Function Parameters

So, how do you properly allocate a function passed as a parameter in a class constructor and then render it to the HTML’s onclick atttribute?

For reference, here’s my code.

class Button {
    constructor(id, btnFunction, btnLabel, additionalStyles = ""){
      this.id = id;
      this.btnFunction = btnFunction;
      this.btnLabel = btnLabel;
      this.additionalStyles = additionalStyles;
    }
  renderBtn(){
    return `
      <button id="${this.id}" onclick="${this.btnFunction}" style="${this.additionalStyles}">${this.btnLabel}</button>
    `;
  }
}
const locationSet = [
  {
    name: "startmenu",
    buttons: [new Button("start", beginGame, "BEGIN GAME", "display: block; margin: auto;")],
    buttonPointers: [document.getElementById("start")],
    text: "Welcome to the RPG test game. I'm currently building something in the moment, so just hang tight and enjoy. Take a look around if you want.",
    colorPalette: () => {
      document.querySelector(':root').style.setProperty('--page-background', '#444');
      document.querySelector(':root').style.setProperty('--textbox-color', '#090');
      document.querySelector(':root').style.setProperty('--game-text', "#fff");
    }
  }
];
//Begins Game Function
function beginGame() {
  console.log("Working.");
  // update(locationSet[1]);
}

If needed, here’s my pen link: https://codepen.io/CasualWanderer20XX/pen/qBzvGJB?editors=0011

if you use an html attribute, you need to put the function name and call it, what you are doing is stringifying the function and is not going to give the effect you want

1 Like

Got it.

Do I need to keep the interpolation?
Should I omit the quotations?

Update: I just decided to botch the html onclick attribute and try something else.

Thanks for the help.

Actually, i decided to botch the html onclick attribute,
but I think i found my solution.

function renderButtons(location) {

  // Clean Control Section First
  controlSection.innerHTML = "";
  buttonPointers = [];
    for (let i = 0; i < location.buttons.length; i++){
      controlSection.innerHTML += location.buttons[i].renderBtn();
      
      
    };
  for (let i = 0; i < location.buttons.length; i++){
    document.getElementById(location.buttons[i].getID()).addEventListener("click", location.buttons[i].getFunction());
  }
};

Use the JS onclick/addeventlistener, and carry out the creation of buttons and assigning DOM references in 2 diffferent for loops.