在 drop() 中访问加载的 Table

Accessing a loaded Table in drop()

我正在尝试通过 p5 中的 drop() 函数在我的草图中加载一个简单的 CSV 文件。我可以成功 'get' 文件并调用 loadTable(),但是我想自动对加载的 table 做一些事情,出于某种原因,我似乎必须让 drop() 函数在能够访问 table.

之前完全完成

我的小测试草图 'gets' 一个被拖到 canvas 上的文件,将其加载到 table 中,并尝试在 getRowCount() 之后立即打印出来加载。这个 returns 0.... 所以我还设置了一个函数 运行 getRowCount() 当鼠标被点击时,这按预期工作。

我的测试 CSV 文件:https://drive.google.com/open?id=1NOluhKiqMxZy10s3dAFLsHLLjoAtV6GT

我只是部分理解为什么会这样,而且我绝对不知道如何解决它。我一直在自学 Javascript 和 p5,所以我不知道我需要搜索哪些术语才能了解这里发生的事情...

var myTable;

function setup() {
  var canvas = createCanvas(400, 400);
  canvas.drop(getFile);
}

function draw() {
  background(220);
}

function getFile(file) {
    myTable = loadTable(file.data);

    // Do something with the table *when* I drop it...
    console.log("In getFile function: " + myTable.getRowCount());

    // Doesn't work either...
    extra(myTable);
}

function mouseClicked() {
    console.log("On mouse click " + myTable.getRowCount());
}

function extra(table_) {
    console.log("In extra function: " + table_.getRowCount());
}

当您对 P5.js 的工作原理有疑问时,我建议您始终查看 the reference

HereloadTable() 函数的参考。它说:

This method is asynchronous, meaning it may not finish before the next line in your sketch is executed. Calling loadTable() inside preload() guarantees to complete the operation before setup() and draw() are called.

Outside of preload(), you may supply a callback function to handle the object:

Syntax

loadTable(filename, options, [callback], [errorCallback])
loadTable(filename, [callback], [errorCallback])

您需要提供一个回调函数,当 loadTable() 函数完成时触发 异步 加载 table.