Yourchingoo
Yourchingoo

Reputation: 3

"Uncaught TypeError: Cannot read property 'bind' of undefined" on p5.js

I'm using p5.js to use button interactions with sprites. I just have a quick question regarding button creation through for-loops. I know that I can easily create separate objects for each of the 4 buttons, but I wanted to see how it would work this way just to make the code shorter.

I want to make the buttons each call one function "puton(i)" with an incremented i in the for loop, so that each button can do something different (which in my case is putting on different clothes). But, I get this error:

Uncaught TypeError: Cannot read property 'bind' of undefined.

I don't really understand too well how parameters work in javascript, so I could be approaching this terribly wrong, so some insight on a more effective approach (besides hard coding each button) would also be appreciated.

Thanks in advance!

var hat, shirt, pants, shoes;

function setup(){
    createCanvas(500, 300);
    background(155);

    var clothes = ["Hat", "Shirt", "Pants", "Shoes"]; // Just to make the code clean.
    for(var i = 0; i < clothes.length; i++){
        var change = createButton('Put on ' + clothes[i]);
        change.position(10, i*30 + 60);
        change.mousePressed(puton(i));
    }
}

function puton(i){
    console.log(i); //To test, "0" gets printed, but after that it crashes.
}

Upvotes: 0

Views: 2909

Answers (1)

paulgv
paulgv

Reputation: 1828

.mousePressed() takes a function as its parameter, not a function call. There's a good example in the official documentation : https://p5js.org/reference/#/p5.Element/mousePressed

This would work in your case :

change.mousePressed(puton);

Or even this :

change.mousePressed(function(e) {
    console.log(e);
});

Upvotes: 2

Related Questions