Sending Multiple Callbacks in your HTML menus

I have many times posted (in this category) about how easy to is to convert to&from JSON and Hashes, Structs and OpenStructs in Ruby.

On the JavaScript side, a JSON string is a definition of a JavaScript Object ready to be evaluated directly into a JS object.
Basically a JS Object definition looks just like a Ruby Hash definition. But it has the added benefit of automatic dot notation access (via keys) to any of the members like a Ruby Struct or OpenStruct has.

So the basic premise I want to get across to you (again) is on the Ruby-side instead of using individual named @vars, to use a Hash, Struct or OpenStruct, whose keys are the option names.
Then to send this data set over to the Html/JS-side, you simply use the data set object’s #to_json method, that is added by Ruby’s JSON library, to create a JSON string that’ll be sent over via the dialog object’s #execute_script method to a JS loader function.

dialog.execute_script("load_options('#{@options.to_json}');")

Now on the JS/HTML side you’ll have a JS Object whose keys will have the same names as they do on the Ruby-side. In addition, the actual HTML form control elements will have corresponding IDs assigned.

This will allow a JS iterator loop to be used to “lookup” each element and attach the change listeners, as well as set each control element’s initial value from that sent over from Ruby. (Right now your writing oodles and oodles of code with a statement to get or set each and every HTML control element value. Not needed if the IDs and data object property names are the same.)
You use the data object’s property names (keys) to lookup the corresponding element’s in the page’s DOM.

  • It would better if I write up an example an post in another thread or maybe a Git repo.

There are a number of examples on StackOverflow for the JS Object ↔ HTML element binding part and attach change event listeners.

For sending back to Ruby you can pass objects back via the sketchup.my_ruby_callback() function call. As noted in the SUAPI doc …

Basic types such as booleans, numbers, strings, arrays and hashes are automatically converted between Ruby and JavaScript.

That sentence should actually say “between JavaScript and Ruby” because that is way the communication is going. It mentions hashes, but JS has Objects, so if you pass your JS-side option data object back, the UI::HtmlDialog callback mechanism will convert it to a Ruby hash.

sketchup.options_update_callback(options_data)

Then you can merge that temp hash parameter with your persistent Ruby-side options hash within the callback block …

# options_update_callback's block:
@options.merge(hash_param)
# maybe do something with the new set of options ?

For a more complex example you might consider using Aerilius’ bridge …

1 Like