Cell reports an error when page is first loaded

Hi,

I’m trying to use contenteditable to make an HTML table editable and then use that table to update an array of objects reflecting the content of the table.

My notebook seems to work EXCEPT for when it’s first loaded…

To get it working I go into the tableData cell and re-run that cell by clicking the little play button and then edit the table and everything from then on is fine.

What am I missing here?

Thanks in advance for any help or suggestions.

Tom

Hi there!

In your notebook, Observable doesn’t know that the tableData cell depends on the table cell so it tries to evaluate it too early, which results in an error.

You get better behavior by adding in an explicit dependence:

I also copied this line:

notify(parseTableData('data-table'));

outside the keyinput event so that the cell will grab the initial data when it first loads, otherwise the cell will wait unresolved until an input is received.

1 Like

Thankyou! Fantastic!
I figured it was something like that but didn’t know how to go about fixing it.

A follow up question; I’ve seen this kind of thing in other notebooks …

tableData = { 
   return 'something'
}

which results in the value of tableData being ‘something’
but I’m not really clear what’s going on. Is this equivalent to the following in a normal bit of JS/ES?

tableData = (function(){ return 'something' }());

?

Thanks again!

Pretty close! If you click on the three dots in the upper right and select “Download code”, you’ll get a link to the notebook “module” object that the Observable runtime parses:

https://api.observablehq.com/@tomgp/editable-table.js

Check out the tableData cell:

    {
      name: "tableData",
      inputs: ["table","Generators","parseTableData"],
      value: (function(table,Generators,parseTableData)
{
  table;
  return Generators.observe(notify => {
    const keyinput = event => {
      notify(parseTableData('data-table'));
    };
    document.querySelector('#data-table').addEventListener("input", keyinput, false);
    notify(parseTableData('data-table'));
    return () => window.removeEventListener("input", keyinput);
  });
}
)
    }

Note that Observable rewrites the cell into a function with several inputs (which correspond to other functions / cells).

1 Like

To add to @bgchen’s recommendation, you can avoid document.querySelector altogether. Here’s a diff you can merge:

1 Like

Also, since you piqued my interest :stuck_out_tongue_winking_eye:, here’s a different take on an editable table expressed as an Observable view:

2 Likes

Many thanks people! I’ve learned a lot today :smile: