inblank
inblank

Reputation: 416

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

I'm facing a problem where I'm trying to instantiate an object inside the setup function of p5, using a callback to do so:

This is the part of sketch.js relevant to the problem:

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]);
    }
}

I already checked using console.log() and the content of the file is being correctly loaded, and the values are correct in what I was expecting. the Graph() class is in another file, but it is being imported as well as the sketch.js. I also tried to put the script importing at the end of the page, but got the same result, the g is still saying undefined.

What I didn't try is to put the whole code of my Graph class into the sketch.js file, but I will need to put more 15 algorithms on the class later, so the sketch file will grow in a unneeded size. I thought the by declaring g as a global variable I would have no problems with it.

I'm fairly inexperienced with JavaScript, so this is probably a rookie mistake about some kind of loading order, so please, if you answer this question, show me the why it is not working as it is. If there's need of any other piece of code, please let me know.

Thanks in advance.

Upvotes: 1

Views: 45

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42176

Looking at this line:

g = Graph(digraph, v);

I think you meant to do this:

g = new Graph(digraph, v);

This creates a new instance and stores a reference to that instance in the g variable.

Upvotes: 1

Related Questions