1

I tried to make a small game using DroidScript on Android. It uses Javascript.

It's a card game. Each button represents a card from the deck. When I touch a button, I expect that app will show popup with the value of the button (card) I have touched.

function callbackFunction( value )
{
    app.ShowPopup(value);
}

//Called when application is started.
function OnStart()
{
    //Create a layout with objects vertically centered.
    lay = app.CreateLayout( "linear", "VCenter,FillXY" );   

    var deck = [1,2,3,4,5,6,7,8,9,10];

    for (var card of deck)
    {
        var btn = app.CreateButton(card.toString(), 0.3, 0.1);
        btn.SetOnTouch( callbackFunction );
        lay.AddChild(btn);
    }

    //Add layout to app.    
    app.AddLayout( lay );
}

But that doesn't output anything because I can't pass value into the callback function. So I tried using an array of buttons:

//Called when application is started.
function OnStart()
{
    //Create a layout with objects vertically centered.
    lay = app.CreateLayout( "linear", "VCenter,FillXY" );   

    // Deck array
    var deck = [1,2,3,4,5,6,7,8,9,10];

    // array of buttons
    var btns = [];

    for (var card of deck)
    {
        var btn = app.CreateButton(card.toString(), 0.3, 0.1);
        btns.push(btn);
        btns[btns.length - 1].SetOnTouch( 
            () => { app.ShowPopup(btns[btns.length - 1].GetText())} );
        lay.AddChild(btns[btns.length - 1]);
    }

    //Add layout to app.    
    app.AddLayout( lay );
}

The problem is, every time I touch any button, the app will show "10". Basically I want the callback to be called with the value of the card as argument. So I tried this:

button.SetOnTouch( callbackFunction( button.GetText() );

But that is not accepted as callback. I really don't know how to pass the value into the callback function.

sanitizedUser
  • 1,723
  • 3
  • 18
  • 33

1 Answers1

2

You can very simply refer to the button, by doing this:

function callbackFunction(){
 var button = this;
 var name = this.GetText();
}

You can also save your own data to a button or any kind of object:

var deck = [1,2,3,4,5,6,7,8,9,10];

    for (var card of deck)
    {
        var btn = app.CreateButton(card.toString(), 0.3, 0.1);
        btn.SetOnTouch( callbackFunction );
        btn.name = card.toString();
        btn.index = deck.indexOf(card);
        lay.AddChild(btn);
    }

You can anyway use an array to save buttons(better to use the first solution I provided you), by doing this:

// Deck array
    var deck = [1,2,3,4,5,6,7,8,9,10];

    // array of buttons
    var btns = [];

    for (var card of deck)
    {
        var btn = app.CreateButton(card.toString(), 0.3, 0.1);
        btns.push(btn);
        eval("btns["+(btns.length - 1)+"].SetOnTouch(function(){callbackFunction("+card.toString()+");} );");
        lay.AddChild(btns[btns.length - 1]);
    }

function callbackFunction(name){
  app.ShowPopup(name);
}