From c5614bfc952ebfc23861cf2e3b73b93a529dd1c4 Mon Sep 17 00:00:00 2001 From: Cory LaViska Date: Thu, 11 Mar 2021 08:57:33 -0500 Subject: [PATCH] only run handler after first render --- docs/getting-started/changelog.md | 1 + src/internal/decorators.ts | 12 ++++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/getting-started/changelog.md b/docs/getting-started/changelog.md index 138fe912..d8d81771 100644 --- a/docs/getting-started/changelog.md +++ b/docs/getting-started/changelog.md @@ -11,6 +11,7 @@ _During the beta period, these restrictions may be relaxed in the event of a mis - Add touch support to `sl-rating` [#362](https://github.com/shoelace-style/shoelace/pull/362) - Fixed a bug where the `open` attribute on `sl-details` would prevent it from opening [#357](https://github.com/shoelace-style/shoelace/issues/357) - Fixed event detail type parsing so component class names are shown instead of `default` +- Improved `@watch` decorator so watch handlers don't run before the first render ## 2.0.0-beta.30 diff --git a/src/internal/decorators.ts b/src/internal/decorators.ts index 786631a2..5defa47b 100644 --- a/src/internal/decorators.ts +++ b/src/internal/decorators.ts @@ -86,6 +86,9 @@ export function tag(tagName: string) { // @watch decorator // +// Runs when an observed property changes, e.g. @property or @internalProperty. This will only run after the first +// update, so initial values will not trigger the watch function. +// // Usage: // // @watch('propName') handlePropChange(oldValue, newValue) { @@ -94,10 +97,15 @@ export function tag(tagName: string) { // export function watch(propName: string) { return (protoOrDescriptor: any, name: string): any => { - const update = protoOrDescriptor.update; + const { firstUpdated, update } = protoOrDescriptor; + + protoOrDescriptor.firstUpdated = function (changedProps: Map) { + firstUpdated.call(this, changedProps); + this.__didFirstUpdate = true; + }; protoOrDescriptor.update = function (changedProps: Map) { - if (changedProps.has(propName)) { + if (this.__didFirstUpdate && changedProps.has(propName)) { const oldValue = changedProps.get(propName); const newValue = this[propName];