Get info from ruby action callback to javascript

The onCompleted callback on JS should be able to receive the return value from Ruby, so if you pull data from JS you don’t need to use execute_script to push the result back from Ruby:

Something like this (untested):

Ruby:

dialog.add_action_callback("layers_to_form") {|action_context|
  # This returns a JSON string from this callback.
  Sketchup.active_model.layers.map(&:name).to_json
}

JavaScript :

function listOfLayers () {
  sketchup.layers_to_form({
    onCompleted: function(json) {
      var layersReceived = JSON.parse(json); # Parse the JSON here
      var arrayLength = layersReceived.length;
      var layerList = "<option value='0'>select layer</option>";
      for (var i = 0; i<arrayLength; i++) {
          layerList += "<option value='"+i+"'>"+layersReceived[i]+"</option>";
      }
      document.getElementById('id10').innerHTML = layerList;
    }
  });
}

If you return only simple values, (not arrays or hashes etc) you shouldn’t even need to return a JSON string, SU should take care of string and numeric conversions for you. (Might not even be necessary to do to_json on that array in this example)

2 Likes