【发布时间】:2022-02-14 01:09:46
【问题描述】:
我正在使用 TypeScript 处理 Web 应用程序的客户端。
我有自己的“框架”,我在其中开发了一个类 (ViewBinder),它使用异步“显示”方法从服务器加载信息、提取 HTML 并将其插入到父“占位符”内的文档中元素。然后,它的派生类可以将数据从客户端状态对象“绑定”到加载的 HTML。
以下是该类的一些代码供参考(不是可执行示例):
export class ViewBinder extends PropertyChangedNotifier {
// Lots of member stuff not shown for brevity...
public async show(callbackAfterShow?: (wasSuccessful: boolean) => void): Promise<HtmlLoadViewResult> {
this.showWasCanceled = false;
const loadResult = await this.loadView();
if (this.showWasCanceled) { // Helps my situation some but not fully
// If this.clear() was called during loadView, we just move on...
loadResult.wasCanceled = true;
} else {
// HERE is where I can have a problem: if this.clear() is called
// while a derived class is doing its setupAfterShowing, the underlying
// HTML will be removed and the attempt to setup (binding data to the
// HTML) will cause an unwanted error.
await this.setupAfterShowing(loadResult);
// CODE REMOVED FOR BREVITY
}
return loadResult;
}
public clear(): void {
// If the show function is awaiting anything, tell it it was canceled
// BUT: what I WANT to do is somehow wait until show() is done before
// continuing the execution of this function... see the question text
this.showWasCanceled = true;
this.localViewBinders.forEach((viewBinder) => viewBinder?.clear());
this.localBindingContexts.forEach((context) => context?.clear());
if (this.parentElement) {
this.parentElement.innerHTML = "";
if (this.isModalDialog) {
this.parentElement.remove();
} else {
this.collapse();
}
this.parentElement = null; // We are no longer associated with the element
this.notifyPropertyChanged("visibility");
this.removeAllPropertyChangedListeners();
}
}
}
请注意,派生类将开发 setupAfterShowing 方法,将数据从客户端状态对象“绑定”到已加载的 HTML(并且可以在它们自己的“子”ViewBinders 上调用 show)。还有一个 clear 命令从父元素中删除所有 HTML 并清除所有“数据绑定”。
但是,当 ViewBinder 等待show 命令(在loadView 或setupAfterShowing 调用期间)时,底层客户端状态对象很少发生更改,这些更改会导致代码调用@987654328 @ 方法,删除父元素的主体,它应该插入它的 HTML 并绑定数据。
一般来说,如果 ViewBinder 找不到父元素或无法在该元素中找到显示数据的位置,我认为这是一个错误并抛出错误。然而,在这种情况下,当异步代码等待结果时,HTML 将被“合法地”删除。
请注意,我已尝试使用 showWasCanceled 来避免此问题,但在派生的 setupAfterShowing 方法中存在太多潜在问题的情况,以确保在 showWasCanceled 设置为 @987654332 时我总是中止@。
所以,这是我的问题:
有没有办法让我的clear 函数确定show 函数是否“正在等待”并暂停执行直到“显示”完成?
【问题讨论】: