How to disable a button when clicked?

2019-07-09 02:07发布

问题:

I create a form using the following code

var app = UiApp.createApplication();
app.setTitle('My Title');
app.setHeight(150);
app.setWidth(300);

var form = app.createFormPanel();
var flow = app.createFlowPanel();

flow.add(app.createHidden("action", action));
flow.add(app.createLabel('My Label'));

//Submit
var submit = app.createButton('Run', app.createServerHandler('myFunction').addCallbackElement(form)).setId('run');
flow.add(submit);

form.add(flow);
app.add(form);

//return app;
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
spreadsheet.show(app);

In myFunction, the button click handler, I try to refer to my button using the following code

function myFunction(e) {
  var app = UiApp.getActiveApplication();
  var submitButton = app.getElementById('run');
  try{
    submitButton.setEnabled(false);
  }finally{
    submitButton.setEnabled(true);
  }
}

But it doesn't work. I get the following execution log (not the Logger.log logging, but I mean the execution logging that can be shown from View > Execution transcript)

[14-07-03 11:04:44:091 SAST] Starting execution
[14-07-03 11:04:44:124 SAST] UiApp.getActiveApplication() [0 seconds]
[14-07-03 11:04:44:125 SAST] (class).getElementById([fetch]) [0 seconds]
[14-07-03 11:04:44:125 SAST] (class).setEnabled([false]) [0 seconds]
[14-07-03 11:04:44:126 SAST] (class).setEnabled([true]) [0 seconds]
[14-07-03 11:04:44:127 SAST] Execution succeeded [0.002 seconds total runtime]

But the button NEVER gets disabled ! How can I disable it when its click handler is fired ?

回答1:

You can use a clientHandler to do that more simply (and also more reliably since client handlers react instantaneously !)

simply add it to your button like this :

  var app = UiApp.createApplication();
  app.setTitle('My Title');
  app.setHeight(150);
  app.setWidth(300);

  var form = app.createFormPanel();
  var flow = app.createFlowPanel();

  flow.add(app.createHidden("action", 'action'));
  flow.add(app.createLabel('My Label'));

  //Submit
  var submit = app.createButton('Run', app.createServerHandler('myFunction').addCallbackElement(form)).setId('run');
  var cliHandler = app.createClientHandler().forEventSource().setEnabled(false);
  submit.addClickHandler(cliHandler);
  flow.add(submit);

  form.add(flow);
  app.add(form);
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  spreadsheet.show(app);

Note also that forms normally use submitButton to work as expected... read the doc about it.

EDIT : to re-enable in the server handler function :

var app = UiApp.getActiveApplication();
app.getElementById('run').setEnabled(true);
return app;