Safe getElementById or try to determine if ID exis

2020-03-24 08:53发布

Method UiInstance.getElementById(ID) always returns GenericWidget object, even if ID does not exist.

Is there some way how to find out that returned object does not exist in my app, or check whether UI contains object with given ID?


Solution for UI created with GUI builder:

function getSafeElement(app, txtID) {
    var elem = app.getElementById(txtID);
    var bExists = elem != null && Object.keys(elem).length < 100;
    return bExists ? elem : null;
}

It returns null if ID does not exist. I didn't test all widgets for keys length boundary, so be careful and test it with your GUI.

EDIT: This solution works only within doGet() function. It does not work in server handlers, so in this case use it in combination with @corey-g answer.

2条回答
劫难
2楼-- · 2020-03-24 09:16

My initial solution is wrong, because it returns false exist controls.

A solution, based on Corey's answer, is to add the setTag("") method and here is ready to use code. It is suitable for event handlers only, because uses tags.

function doGet() {
  var app = UiApp.createApplication();
  var btn01 = app.createButton("control01").setId("control01").setTag("");
  var btn02 = app.createButton("control02").setId("control02").setTag("");
  var handler = app.createServerHandler("clicked");
  handler.addCallbackElement(btn01);
  handler.addCallbackElement(btn02);
  btn01.addClickHandler(handler);
  btn02.addClickHandler(handler);
  app.add(btn01);
  app.add(btn02);
  return app;
}

function clicked(e) {
  var app = UiApp.getActiveApplication();
  app.add(app.createLabel("control01 - " + controlExists(e, "control01")));
  app.add(app.createLabel("control02 - " + controlExists(e, "control02")));
  app.add(app.createLabel("fake - " + controlExists(e, "fake")));
  return app;
}

function controlExists(e, controlName) {
  return e.parameter[controlName + "_tag"] != null;
}
查看更多
等我变得足够好
3楼-- · 2020-03-24 09:18

This will only work in the same execution that you created the widget in, and not in a subsequent event handler where you retrieve the widget, because in that case everything is a GenericWidget whether or not it exists.

You can see for yourself that the solution fails:

function doGet() {
  var app = UiApp.createApplication();
  app.add(app.createButton().setId("control").addClickHandler(
      app.createServerHandler("clicked")));
  app.add(app.createLabel(exists(app)));
  return app;
}

function clicked() {
  var app = UiApp.getActiveApplication();
  app.add(app.createLabel(exists(app)));
  return app;
}

function exists(app) {
  var control = app.getElementById("control");
  return control != null && Object.keys(control).length < 100;
}

The app will first print 'true', but on the click handler it will print 'false' for the same widget.

This is by design; a GenericWidget is a "pointer" of sorts to a widget in the browser. We don't keep track of what widgets you have created, to reduce data transfer and latency between the browser and your script (otherwise we'd have to send up a long list of what widgets exist on every event handler). You are supposed to keep track of what you've created and only "ask" for widgets that you already know exist (and that you already know the "real" type of).

If you really want to keep track of what widgets exist, you have two main options. The first is to log entries into ScriptDb as you create widgets, and then look them up afterwards. Something like this:

function doGet() {
  var app = UiApp.createApplication();
  var db = ScriptDb.getMyDb();
  // You'd need to clear out old entries here... ignoring that for now
  app.add(app.createButton().setId('foo')
      .addClickHandler(app.createServerHandler("clicked")));
  db.save({id: 'foo', type: 'button'});
  app.add(app.createButton().setId('bar'));
  db.save({id: 'bar', type: 'button'});
  return app
}

Then in a handler you can look up what's there:

function clicked() {
  var db = ScriptDb.getMyDb();
  var widgets = db.query({}); // all widgets
  var button = db.query({type: 'button'}); // all buttons
  var foo = db.query({id: 'foo'}); // widget with id foo
}

Alternatively, you can do this purely in UiApp by making use of tags

function doGet() {
  var app = UiApp.createApplication();
  var root = app.createFlowPanel();  // need a root panel
  // tag just needs to exist; value is irrelevant.
  var button1 = app.createButton().setId('button1').setTag(""); 
  var button2 = app.createButton().setId('button2').setTag("");
  // Add root as a callback element to any server handler
  // that needs to know if widgets exist
  button1.addClickHandler(app.createServerHandler("clicked")
      .addCallbackElement(root));
  root.add(button1).add(button2);
  app.add(root);
  return app;
}

function clicked(e) {
  throw "\n" +
      "button1 " + (e.parameter["button1_tag"] === "") + "\n" + 
      "button2 " + (e.parameter["button2_tag"] === "") + "\n" + 
      "button3 " + (e.parameter["button3_tag"] === "");
}

This will throw:

button1 true
button2 true
button3 false

because buttons 1 and 2 exist but 3 doesn't. You can get fancier by storing the type in the tag, but this suffices to check for widget existence. It works because all children of the root get added as callback elements, and the tags for all callback elements are sent up with the handler. Note that this is as expensive as it sounds and for an app with a huge amount of widgets could potentially impact performance, although it's probably ok in many cases especially if you only add the root as a callback element to handlers that actually need to verify the existence of arbitrary widgets.

查看更多
登录 后发表回答