Pass variable from button

How do you pass a variable from a button? as in:
var button = BABYLON.GUI.Button.CreateSimpleButton(“but”, “Click Me”);
button.mesh_type =“unit”;

button.onPointerDownObservable.add(function () {
	console.log(this.mesh_type);
});

“this” doesn’t work

this here would refer to the source not the current this. :slight_smile:

sorry basically you can use () => { } instead of function() { } to access the this you are expecting:

or you can capture another variable:
var mtype = this.mesh_type;
button.onPointerDownObservable.add(function () {
console.log(mtype);
});

Lets say I have an array of buttons, how do I assign onPointerdown to them all but access individual variables in the function?

var button = new Array;
for(vari=1; i<=10; i++){
button.id = i;
button.onPointerDownObservable.add(function () {
console.log(this.id);
});
}

replace this.id by button.id in the console.log

this isn’t going to work, the button need to be able to identify itself to the function (sorry left out the array brackets and index)

var button = new Array;
for(var i=1; i<=10; i++){
button[i].id = i;
button.onPointerDownObservable.add(function () {
console.log(button[i].id );
});
}

This works if you replace for var in for let due to capture in javascript else you ll always have i=10 in the callback https://www.babylonjs-playground.com/#XCPP9Y#822

also you do not need the array at all:
https://www.babylonjs-playground.com/#XCPP9Y#826

I see , I can use the button.name as a key to access other data…Thanks!

You can also use function.bind() :slight_smile:

button.onPointerDownObservable.add(function () {
	console.log(this.mesh_type);
}.bind(button));

That’s better because I can use the button to hold the variable rather than a separate hash