Home > Mobile >  Pass function as argument to another function called inside the first one
Pass function as argument to another function called inside the first one

Time:11-03

I have a function that creates a button with an "onclick" action that calls a second function. This second function will recieve parameters of the first one (includind a function). Just like this:

function funcOne(argFunc, customMsg) {
    let div = document.createElement('div');
    let button = `<button onclick='funcTwo(` argFunc `','` customMsg `)'>Go!</button>`;
    div.innerHTML = button;
    document.body.appendChild(div);
}

function funcTwo(argFunc, customMsg) {
    argFunc(customMsg);
}

Then, calling funcOne:

funcOne(function(customContent) { alert(customContent) },
'Hello World');

I get "Uncaught SyntaxError: Unexpected end of input" error here:

let button = <button onclick='funcTwo( argFunc ',' customMsg )'>Go!</button>;

CodePudding user response:

In general, avoid onxyz-attribute-style event handlers. Always avoid them when you have a function (rather than string) you need to hook up dynamically. They have several issues, not least that they can only call global functions.

Instead, use modern event handling. There's also no need for HTML parsing:

function funcOne(argFunc, customMsg) {
    const div = document.createElement("div");
    const button = document.createElement("button");
    button.textContent = "Go";
    button.addEventListener("click", () => {
        funcTwo(argFunc, customMsg);
    });
    div.appendChild(button);
    document.body.appendChild(div);
}

function funcTwo(argFunc, customMsg) {
    argFunc(customMsg);
}
  • Related