How to know when a property has been updated from it's connected attribute?

272 Views Asked by At

Given:

@property({type: Boolean, attribute: 'some-attr'}) someAttr = false;

I was expecting to see updated being fired once 'some-attr' value gets updated in the DOM.

However, updated doesn't get fired at all.

Is my expectation wrong, or should I set things up differently?

1

There are 1 best solutions below

1
On

Looking at Elm's discussion of properties vs attributes, the documentation of the Html.Attributes module's attribute function, and the Elm documentation on custom elements, I am pretty sure, that this is caused by simply binding an elm expression to attribute some-attr of the LitElement based custom element. I.e. the DOM attribute will always be present and hence the corresponding property always be true.

The default converter for Boolean (activated by providing type:Boolean to the decorator) mimicks the behaviour of HTML attributes used as flags (e.g. disabled on an <input> element): If the attribute is present (no matter the value), the flag is set (true). The implementation is really straight forward, if you want to look at it in the sources: https://github.com/Polymer/lit-element/blob/master/src/lib/updating-element.ts#L163

I see these options for your problem:

  1. Implement some extra logic in Elm to add / remove the presence of the attribute.
  2. Create your own attribute converter for the LitElement based custom element.
  3. Use another default converter (e.g. for String, the "default" default converter) and implement the custom logic inside the LitElement (e.g. using a derived value).

Of these 3 options, I would generally recommend the first one, as your custom element then still behaves naturally, i.e. if some-attr should be a flag (boolean attribute), then following which HTML semantics, it should be defined by its presence, not its value. This allows you to re-use it in other projects without surprising other developers.

That being said, there may of course be project-specific requirements, that are more important. E.g. if you only use this custom element in this one project with Elm, your road to success may be faster going for options 2 or 3.