通过 p5 上 set up() 中的 DOM 元素实例化一个对象

Instanciating an object via DOM element inside setup() on p5

我遇到一个问题,我试图在 p5 的设置函数中实例化一个对象,使用回调来执行此操作:

这是sketch.js中与问题相关的部分:

var g; //for graph instance
var dropzone; //for the file dropping area

function setup() {
    createCanvas(640, 480);

    dropzone = select('#dropzone'); //selects the <p> element I'm using as dropzone
    dropzone.drop(process_file, unhighlight); //unhighlight is just a function to make the drop area not-highlighted
}

function draw() {
    background(200);
    if (g) {
        g.show();
    }else{
        msg = "Please, load a file by dropping it in the box above";
        text(msg, width/2, height/2);
    }
}

// callback being used to process the text file content
function process_file(file){
    data = file.data; //gets file data(content)
    lines = data.split('\n'); // split the lines
    digraph = lines[0] == 1 ? true : false; // is it a digraph?
    v = int(lines[1]);
    g = Graph(digraph, v); //the class I"m using to instantiate the graph
    console.log(g); // <-- says undefined
    g.init_graph(); // initialize all vertices
    for (var i = 2; i < lines.length; i++) {
        edge = lines[i].split(' ');
        g.add_edge(edge[0], edge[1], edge[2]);
    }
}

我已经使用 console.log() 进行了检查,文件内容已正确加载,值也符合我的预期。 Graph() class 在另一个文件中,但它与 sketch.js 一样被导入。我也试过把脚本导入放在页面的末尾,但得到了同样的结果,g 仍然是 undefined

我没有尝试将 Graph class 的全部代码放入 sketch.js 文件中,但我需要在 class 中放入更多 15 种算法稍后,草图文件将以不需要的大小增长。我认为通过将 g 声明为全局变量我不会有任何问题。

我对 JavaScript 相当缺乏经验,所以这可能是关于某种加载顺序的菜鸟错误,所以如果你回答了这个问题,请告诉我为什么它不能正常工作是。如果需要任何其他代码,请告诉我。

提前致谢。

查看这一行:

g = Graph(digraph, v);

我想你是想这样做:

g = new Graph(digraph, v);

这将创建一个新实例并将对该实例的引用存储在 g 变量中。