-->

How to attach a callback to a custom confirmation

2019-03-02 11:12发布

问题:

I am creating a custom confirmation dialog in Google App Maker and would like the Confirm button to call a passed-in function. I don't see an "onclick" event in the button widget. Any suggestions on how to do this?

function confirmationDialog(msg, confirmFunction)
{
  var desc = app.pageFragments.ConfirmationDialog.descendants;
  var label = desc.Label;
  var confirmButton = desc.Confirm;

  label.text = msg;
  confirmButton.onClick = confirmFunction;  // does not work

  app.showDialog(app.pageFragments.ConfirmationDialog);
}

Thanks

回答1:

It'd be great if this was a bit easier, but the best bet is to use Custom Properties (https://developers.google.com/appmaker/ui/viewfragments).

You can set up a custom property of type "Dynamic" and call it anything, take "onConfirmCallback", for example. Then you can set the function on that custom property:

Code to invoke dialog:

app.pageFragments.ConfirmationDialog.properties.onConfirmCallback = function(param) {
  alert(param); 
};
app.showDialog(app.pageFragments.ConfirmationDialog);

And then in the onClick for the close button:

app.pageFragments.ConfirmationDialog.properties.onConfirmCallback("hi");
app.closeDialog();

Also note that there are slightly better ways to set up labels than in your example, also using custom properties.

Create custom properties for any widget properties you want to customize, and then bind those custom properties (@properties.propertyName) to the widget property. For example you might have a confirmText property, with the confirm buttons text property boudn to @properties.confirmText.

Then when you invoke your dialog, you can just set those custom properties. Quick modification of your example code using properties for everything:

function confirmationDialog(msg, confirmFunction)
{
  var properties = app.pageFragments.ConfirmationDialog.properties;
  properties.text = msg;
  properties.confirmCallback = confirmFunction;

  app.showDialog(app.pageFragments.ConfirmationDialog);
}


回答2:

For my confirmation dialogs, I just set the onclick of the OK button before I show the dialog (everything is in one place, which is easier for the dummy (me) who will have to maintain it in six months:

  var dialog=app.pages.ConfirmationDialog;
  dialog.descendants.message.text='Are you sure...?'
  dialog.descendants.btnOk.getElement().onclick=function(){
      //do something here
      app.closeDialog();
    });
  };
  app.showDialog(dialog);
}