将WebAssembly模块包装到Web组件中时出现异步问题



我有一个WebAssembly模块,它在HTML5WebGL画布上呈现一些东西。一切正常。但是,我希望将所有内容都封装在一个Web组件中,以简化该模块的使用。

WebAssembly模块相当大,因此需要几秒钟的下载时间。一旦下载完WebAssembly模块,就会调用一个JavaScript回调函数。

在模块下载过程中,向用户提供一些光学反馈,表明发生了一些事情。在下载模块时,我正在画布上绘制动画。该动画在回调函数中停止,模块在那里被实例化。

从概念上讲,我正在努力将JavaScript回调函数与表示Web组件的类相结合。到目前为止,我拥有的是:

// Code that starts downloading the WebAssembly module (asynchronous)
...
var downloadAnimation;
// The class that represents the custom Web Component
class MyWebComponent extends HTMLCanvasElement {
constructor() {
super();
// Initialization
...
}
connectedCallback() {
// Start the animation indicating to the user that a download is in progress
downloadAnimation = new DownloadAnimation(this);
downloadAnimation.start();
}
// custom functions and properties enabling the usage of the WebAssembly module
...
}
// Register the custom Web Component so that instances of it can be created.
// If this were to be done in the onModuleReady callback function there would
// not be an animation that runs while the download is in progress.
if(!customElements.get("MyWebComponent")) {
customElements.define("MyWebComponent", MyWebComponent, { extends: "canvas" });
}
// Called once the WebAssembly module is downloaded, i.e. when we're ready to instantiate it
function onModuleReady() {
// First, the download animation is stopped
downloadAnimation.stop();
// Next, I could instantiate the WebAssembly module as shown below.
// But how do I connect that instance with the instance of the Web Component
// that is created via HTML?
let myWebAssemblyInstance = new Module.MyCustomClass();
}

为了能够运行下载动画,必须在下载WebAssembly模块之前创建Web组件。因此,我不能简单地在onModuleReady回调函数中执行customElements.define。那就太晚了,无法开始动画制作。

下载模块后,我就可以开始创建它的实例了,但我不知道如何将这些实例和通过HTML创建的Web组件实例连接起来。因为我不在代表Web组件的类之外,所以我不知道如何访问它

有没有一种方法可以访问代表这些实例的类之外的Web组件实例,例如从onModuleReady中访问?

或者,更普遍地说,有人看到更好的方法来处理这个问题吗?

让您的组件侦听(在root级别(事件。

onModuleReady然后分派事件,该事件会弹出。

您可能想要CustomEvent:https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent

注意,您需要composed: truefor Events来"逃离"shadowRoots

概念上与标准onloadDomContentLoaded事件没有区别

注:

  • 您不限于CustomEventdetails负载中的DataTypes
    可以添加函数引用
    因此接收方可以在调度事件的元素中执行方法

  • 事件被处理同步

  • 有关深入的事件处理,请参阅:What the heck is the Event Loop
    https://www.youtube.com/watch?v=8aGhZQkoFbQ


另请参阅:https://pm.dartus.fr/blog/a-complete-guide-on-shadow-dom-and-event-propagation/

最新更新