Lifecycle hook upon asyncReplace update or completion #2219
-
I am trying to register a custom click listener for all links that are part of a DOM subtree appended in the lit The problem I have is that the Here is a minimal live example that logs when Is there a way to have a callback called upon |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This is one reason why reactive controllers are in some ways a more powerful tool to handle async values than This is untested, but roughly the idea: class AsyncValue implements ReactiveController {
private _host: ReactiveControllerHost;
private _iterable?: AsyncIterable<T>;
private _cancelIteration?: () => void;
value?: T;
set iterable(v?: AsyncIterable<T>) {
if (this._iterable !== v) {
this._iterable = v;
this._iterate();
}
}
constructor(host: ReactiveControllerHost) {
this._host = host;
host.addController(this);
}
private async _iterate() {
const iterable = this._iterable;
this._cancelIteration?.();
const cancelPromise = new Promise((res, rej) => this._cancelIteration = rej; );
for await (const v of Promise.race([iterable, cancelPromise])) {
if (iterable !== this._iterable) {
return;
}
this.value = v;
this._host.requestUpdate();
}
}
} Then: class MyElement extends LitElement {
private _myValue = new AsyncValue(this);
@property({attribute: false})
someIterable;
render() {
this._myValue.iterable = this.someIterable;
return html`<p>${this._myValue.value}</p>`;
}
} This is a bit more verbose than a directive, so you could also wrap this up in an async directive to create the controller automatically. Another option would be to use something like https://github.com/ReactiveX/IxJS to wrap the iterable with a callback that calls |
Beta Was this translation helpful? Give feedback.
This is one reason why reactive controllers are in some ways a more powerful tool to handle async values than
until
andasyncReplate
. The downside is that controllers trigger entire component updates (which is the point here - so you can tie into the update lifecycle) whereas directives update only one binding in a template. You could make a reactive controller to use instead of asyncReplace.This is untested, but roughly the idea: