0

I have referenced multiple SO questions but I still could not find a solution. These are the questions I took a look at (main ones):

  1. Pass a JavaScript function as parameter
  2. How to execute a method passed as parameter to function

compute.js:

const mainTable = document.getElementById('nonFixedSample');

function getRows(metricName) {
    let row = 0;
    let z = document.getElementsByTagName('tr');
    for (let i = 0; i < z.length; i++) {
        if (mainTable.rows[i].firstChild.textContent === metricName) {
            row = i;
            return row;
        }
    }
}

// Here I am trying to pass that function as callback

function stdCellArea(callback) {
    rowNumber = callback();

    let runs = mainTable.rows[rowNumber].cells.length;
    // Other code
}

Now I am calling it, reg_report.php:

<script>
    stdCellArea(function() {
        getRows('test');
    });
</script>

But I get the following error:

Uncaught TypeError: Cannot read property 'cells' of undefined at stdCellArea (compute.js:17) at reg_report.php:39

Basically, I need to use return value of getRows() as an argument for stdCellArea(). I know I could simply do this:

let x = getRows('text');
stdCellArea(x);

But I have to call this function over 10 times, so I do not want to create many variables. Who can help?

tera_789
  • 489
  • 4
  • 20
  • 1
    What is the reason that you are doing this with a callback rather than calling `getRows()` directly with something like `let rowNumber = getRows('test');`? – Code-Apprentice Oct 09 '18 at 02:49
  • Actually a very good question. I do not know... I decided to go with callback. What would you use in this case? – tera_789 Oct 09 '18 at 02:54
  • I would replace `rowNumber = callback()` with the code I gave in my previous comment. – Code-Apprentice Oct 09 '18 at 02:55
  • Would there be any difference in performance or any difference at all? – tera_789 Oct 09 '18 at 02:56
  • You should worry about how easy it is to understand the code before you worry about performance. Callbacks are an important tool but don't seem like the correct solution here. – Code-Apprentice Oct 09 '18 at 02:56

1 Answers1

3

You need to return the value from your callback: return getRows('test');. Without that, rowNumber becomes undefined as that's what functions without an explicit return, return.

Mrchief
  • 75,126
  • 20
  • 142
  • 189