The error shown in the Chrome Dev panel … "ReferenceError: recibeJSON is not defined"
happens because the JS statement in your HTML string …
document.getElementById('comp').innerHTML = recebeJSON.id;
is evaluating BEFORE the recebeJSON
object is defined.
You are defining it later on the RUBY side AFTER the dialog is shown, and AFTER the above assignment statement.
So it is a issue of timing.
(a)
Put a defining statement at the top of the javascript …
var recebeJSON = {};
(b)
Do not send dynamic data over to the dialog until the dialog reports that it has loaded all the HTML and JavaScript and is ready. To have the dialog report back when ready, do something like this at the bottom of the HTML file …
</body>
<script>
// Load Event
document.body.onload = function() {
sketchup.report_ready();
}
</script>
</html>
And in your Ruby, attach an action callback named “report_ready” to the UI::HtmlDialog
object that sets the initial data for the recebeJSON
JS object and then calls JS function to load the from fields…
dialog.add_action_callback("report_ready"){|action_context|
dialog.execute_script( %[recebeJSON = JSON.parse('#{my_hashjon}');] )
dialog.execute_script( %[load_form();] )
}
Notice that we use %
string delimiters with [
… ]
brackets here so as not to confuse the Ruby interpreter with the nested double quote characters that can be produced by the JSON
string creation.
See the primer on String literals …
File: literals.rdoc [Ruby 2.7.1]
… for an explanation of %Q
(same as %
,) and %q
delimited string literal expressions.
You can also set the fields individually …
dialog.add_action_callback("report_ready"){|action_context|
dialog.execute_script( %[recebeJSON.id = '#{my_hash["id"]}');] )
dialog.execute_script( %[recebeJSON.altura = #{my_hash["altura"]});] )
dialog.execute_script( %[recebeJSON.largura = #{my_hash["largura"]});] )
dialog.execute_script( %[recebeJSON.compr = #{my_hash["compr"]});] )
dialog.execute_script( %[load_form();] )
}
The Javascript load_form()
function would be similar to …
<script>
// Load Form
load_form = function() {
document.getElementById('id').innerHTML = recebeJSON.id;
document.getElementById('id1').innerHTML = recebeJSON.altura;
document.getElementById('id2').innerHTML = recebeJSON.largura;
document.getElementById('id3').innerHTML = recebeJSON.compr;
}
</script>
(c)
You are also not setting the altura (height) and largura (width) in the hash.
my_hash={ id:id, compr:comp, altura: e.bounds.height, largura: e.bounds.width }
Do not change the layer (tag) of geometric primitives. (Leave them on “Layer0” / “Untagged”.)
Only set complex objects to other layer/tags, such as Guides, Dimensions, Group or Component Instances, Section Planes, etc.