Skip to content

Instantly share code, notes, and snippets.

@robdodson
Last active July 8, 2017 17:38
Show Gist options
  • Save robdodson/93d3ec553dcc52477321fa1fd0d46d81 to your computer and use it in GitHub Desktop.
Save robdodson/93d3ec553dcc52477321fa1fd0d46d81 to your computer and use it in GitHub Desktop.

How should Preact handle setting objects and arrays on undefined Custom Element properties?

Example of current behavior.

1. Server side rendering a Custom Element

In this scenario you're just trying to bootstrap a Custom Element with some data so it can render as soon as it hits the page. You don't have the ability to set properties, so serializing objects and arrays to string attributes seems like the only way to do it? Custom Elements could be written to expect this and call JSON.parse on their obj/arr observed attributes.

2. Lazy loading the definition for a Custom Element

In this scenario, the custom element tag might already be on the page, but its definition hasn't been loaded yet so all properties are undefined. In this situation you could either set everything as attributes, or use properties and encourage Custom Element authors to support lazy properties. If you go the attributes route, you probably want to call JSON.stringify on any arrays or objects, otherwise they'll be useless when the element boots up.

3. Custom Element definition has already been loaded

In this case the element should have all of its properties defined. The approach Preact uses here is great! Check if the property is defined and use it, otherwise set as attribute.

However, I don't think Preact has a way of knowing that the element's defintiion has already been loaded (unless they check the customElements registry with whenDefined). Without checking whenDefined for any Custom Element it encounters, I don't see how Preact could differentiate between scenarios #2 and #3. So then we're back to either serializing arrays and objects with JSON.stringify (if the property is undefined) or always setting those as properties and encouraging a lazy properties pattern. Personally I think I'm fine with either approach but I'm curiuos what others prefer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment