Step 4 - Callback Data

If you have two buttons that do something very similar, such as run a GSL example, then it is better to use one callback function for both buttons rather than a callback function for each. One function is easier to maintain than two and if you need to make changes in the future - you only need to do them once instead of twice.

The second argument to a callback function is the callback data. Each GUI object that you create has its own specific data which is passed to the specified callback function. In our example we will use the callback data to specify the name of the example to run.

Replace the following code in myapp.gsa

function RunExampleCB(string o, string d, float r)
  echo("Running example: "+d);
  exec("$UNIDIR/example/Gsharp/"+d);
endfunction
create Menu gsharp_1.Menubar.Demos;
create Button gsharp_1.Menubar.Demos.BarCharts
 ( XuNguiLabel = "Bar Charts",
   XuNguiCallback = "RunExampleCB",
   XuNguiCallbackData = "'samples/barcharts.gsl'"
 );  
create Button gsharp_1.Menubar.Demos.ErrorBars
 ( XuNguiLabel = "Error Bars",
   XuNguiCallback = "RunExampleCB",
   XuNguiCallbackData = "'samples/errorbars.gsl'"
 );  
create Button gsharp_1.Menubar.Demos.ScatterPlots
 ( XuNguiLabel = "Scatter Plots",
   XuNguiCallback = "RunExampleCB",
   XuNguiCallbackData = "'samples/scatterplots.gsl'"
 );  

You see that all of our buttons use the same callback function, RunExampleCB. For each object we have specified the callback data to be the name of the example we would like to run.

Save myapp.gsa and run it again. You will notice that you now have a Demos menu containing three buttons. When you select each button, the appropriate example is run.

So how did this happen?

Each of the buttons uses the same callback RunExampleCB (you don't have to add CB to the end of your function name, but we normally do).

When the button is click on RunExampleCB is executed. If we had clicked on the BarCharts button then the value of RunExampleCB arguments will be:

  • o = "gsharp_1.Menubar.Demos.BarCharts"
  • d = "samples/barcharts.gsl"
  • r = XuCR_ACTIVATE or 10

Our function ignores the values of o and r. It only needs the value of d to know which example to execute.

echo("Running example: "+"samples/barcharts.gsl");
exec("$UNIDIR/example/Gsharp/"+"samples/barcharts.gsl");

You have now created your own first Gsharp Application. It has options to run three Gsharp examples and an Exit option.

Now carry on to Step 5 - Reading and Writing Files