Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure ref value is always undefined when disconnected #4646

Merged
merged 3 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/violet-phones-look.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'lit-element': patch
'lit-html': patch
'lit': patch
---

The value provided by the `ref()` directive will always be `undefined` when the element is disconnected.
3 changes: 3 additions & 0 deletions packages/lit-html/src/directives/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ class RefDirective extends AsyncDirective {
}

private _updateRefValue(element: Element | undefined) {
if (!this.isConnected) {
element = undefined;
}
if (typeof this._ref === 'function') {
// If the current ref was called with a previous value, call with
// `undefined`; We do this to ensure callbacks are called in a consistent
Expand Down
22 changes: 22 additions & 0 deletions packages/lit-html/src/test/directives/ref_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,4 +368,26 @@ suite('ref', () => {
go();
assert.deepEqual(calls, ['DIV', undefined, 'DIV', undefined, 'DIV']);
});

test('set to undefined when disconnected and reset when reconnected', () => {
let value: Element | undefined;
const go = () =>
render(html`<div ${ref((el) => (value = el))}></div>`, container);
const part = go();
assert.equal(value, container.firstElementChild);
part.setConnected(false);
assert.isUndefined(value);
part.setConnected(true);
assert.equal(value, container.firstElementChild);
});

test('always undefined when disconnected', () => {
let value: Element | undefined;
const go = () =>
render(html`<div ${ref((el) => (value = el))}></div>`, container);
const part = go();
part.setConnected(false);
go();
assert.isUndefined(value);
});
});