How to have multiple watched inputs from a single cell?

Is there is any way to have multiple values exported from a given cell?

For instance, if want to make a ui with a bunch of sliders to control values in a simulation the only way I am aware of to do that is each slider in a separate cell. I tried using object unpacking in my cell declaration ala. ({val1, val2}) = { return {val1: 1, val2: 2}} but it was a no-go.

Another way I could think of is to export a raw object and then in subsequent cells pluck of the fields you want, but that feels hacky and I’m not sure it would be smart about updating.

I feel like this may be a trivial question but I read through all the introduction notebooks and couldn’t see anything in this regard.

Thanks!

Instead of

try

    myDict = { 
    # ...
    return {val1: 1, val2: 2};
    }

then in other cells, use myDict.val1, myDict.val2 etc. I saw John Bannister using this in his planets sketch, and I tried it and it works pretty nicely! He was using it to expose callback functions.

1 Like

We don’t support multiple exports from cells yet, but we’ve been considering destructuring exports exactly like you describe. Stay tuned! To continue the example, destructruing would provider shorter syntax equivalent to three cells (where _ is an anonymous cell):

_ = ({val1: 1, val2: 2})
val1 = _.val1
val2 = _.val2

An implication of this design is that all exports (val1 and val2 here) would change simultaneously. Observable doesn’t do any value comparison when a cell yields a new value, so we would conservatively assume that all exported values have changed.

Makes sense. So perhaps a good way to deal with multiple inputs in a single dom element would be to export the DOM object from the cell and then have subsequent cells that pluck off the values of various inputs inside of it?

Yes, that would work. Though I think I would only do that if you need to react to the inputs individually for performance reasons; a compound input with viewof is simpler and should be preferred if it performs acceptably. I’ve written up a summary of possible techniques here:

https://beta.observablehq.com/@mbostock/multi-value-inputs

2 Likes

This is wonderful! Thanks so much! And thanks in general for dedicating your time to this tool. It’s a game changer.

2 Likes