🏠 back to Observable

Cell updates


I’m working on a notebook that includes buttons that call functions to render the content of other cells. The function also includes text referenced from another cell. Here’s an example.

The problem is that every time I edit and update the “prefix” cell it fires the function. The same when I load/reload the page. I only want the function to be fired when the button is clicked. Is there a way to do this.

I need this behaviour so that the notebook doesn’t invoke an HTTP POST until I’m ready.

1 Like

It’s hard to say for sure what the best approach might be, without a more complete understanding of what you’re trying to accomplish. For example, it might be the case that your prefix could be best implemented as a Text input with a submit button. I will say this, though:

While reactive programming in Observable is incredibly easy and convenient for simple things, you can certainly use event listeners for more finely tuned control when necessary.

In your case you might try something like the following:

// Cell 1
prefix = "This is content (try changing it): "

// Cell 2 - output with no dependencies.
pure_output = html`This is not yet content: `

// Cell 3 - a Button with an event listener
  let btn = Button("Wait for Random");
  btn.onclick = function() {
    d3.select(pure_output).text(`${prefix} ${rand()}`)
  return btn

// Cell 4 - Just a little bit of D3
d3 = require('d3-selection@2')

Here’s the complete version:

@carlskii Define the button cell as a dependency of your code-executing cell. Then ensure that your button cell has an initial value of undefined. That way the code won’t execute until the button has been pressed.

Since you’re already using Observable’s Button widget, all you need to add is required: true:

viewof run = Button('Run code!', {required: true})

This sets the button’s initial value to undefined.

For more information on the topic see this notebook:

Thanks for this - this did the trick.

Thanks very much, I’ll also give this approach a try.