is there an alias for a top-level scope?

Sometimes I want to redefine a globally-defined name, but use the global definition to determine the redefinition.

For example …

const width = Math.min(width, 600)

… for a chart that shouldn’t take up the full width on desktop but should on mobile.

Currently this throws an error:
ReferenceError: can't access lexical declaration `width' before initialization

It would be neat if I could instead do something like …

const width = Math.min(global.width, 600)

… or pick your favorite alternate name.

For width specifically, couldn’t you use document.body.clientWidth instead (as in your very useful “Width view” notebook)?

[I would of course be delighted to have more “meta-level” access to the Observable runtime from within notebooks, though none of the uses I have in mind are actually “useful”…]

Yes. That was just an example. I was wondering more generally.

Maybe it’s better to just use a new name instead of trying to replace standard library objects.

Yes, I’ve wanted this, too. Here are some alternatives in the meantime.

You can use a different name:

w = Math.min(width, 640)

You can duplicate the definition of width:

width = Generators.observe(notify => {
  let width;
  function resized() {
    let w = Math.min(document.body.clientWidth, 640);
    if (w !== width) notify(width = w);
  addEventListener("resize", resized);
  return () => removeEventListener("resize", resized);

You can give a static definition (which won’t work if the window is resized, so probably don’t do this):

width = Math.min(document.body.clientWidth, 640)

If you’re using the D3 chart template, you can use the margin to limit the inner width of the chart rather than the outer width:

margin = ({top: 20, right: width - height + 40, bottom: 30, left: 40})

See Q–Q Plot for an example.

1 Like

For width in particular, there’s also:

import {viewof width as width_} from '@jrus/widthview'

Followed by

const width = Math.min(width_, 640);