Search code examples
javascripttabulator

JS passing the forEach variable to the lookup function


Please help me understand how I can pass this argument to the lookup function of the formatter. I try to dynamically create table rows for tabulator:

works:

keys = ["name", "price", "number"];
doAjax().then( variable => { 
    if ( products ) {
        let cols = [{title: "number", field: "number"}];
        keys.forEach(function ( key ) {
            let formatter = "";

            // check if key is number
            if ( key == "number" ) {
                formatter = function( cell ) {
                                return `<div íd="${key}">${cell.getValue()}</div>`;
                            };
            };
            cols.push({title: key, field: "data." + key, formatter: formatter});
         });
    };
 });    

does not work:

let testf = function( cell, key ) { 
    return `<div íd="${key}">${cell.getValue()}</div>`; // key is not accessible here
};

keys = ["name", "price", "number"];
doAjax().then( variable => { 
    if ( products !== null ) {
        let cols = [{title: "number", field: "number"}];
        keys.forEach(function ( key ) {
            let formatter = "";

            // check if key is number
            if ( key == "number" ) {
                formatter = testf(cell, key);  // not working
            };
            cols.push({title: key, field: "data." + key, formatter: formatter});
         });
    };
 });    

code for context:

var table = new Tabulator("#products", {
    ajaxURL: "api/products",
    columns: cols,
});

How could I rewrite the second approach, so it gets the argument key passed along?


Solution

  • Make a function that takes the initial cell as an argument, and calls testf with it and the key.

    if (key == "number") {
        formatter = cell => testf(cell, key);
    };