Skip to content

Commit

Permalink
Ensure ref value is always undefined when disconnected (#4646)
Browse files Browse the repository at this point in the history
* ref always undefined when disconnected

* Update .changeset/violet-phones-look.md

Co-authored-by: Augustine Kim <[email protected]>

* Update .changeset/violet-phones-look.md

Co-authored-by: Augustine Kim <[email protected]>

---------

Co-authored-by: Steve Orvell <[email protected]>
Co-authored-by: Augustine Kim <[email protected]>
  • Loading branch information
3 people committed May 23, 2024
1 parent 2633e76 commit abf30b3
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
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);
});
});

0 comments on commit abf30b3

Please sign in to comment.