我有一个WebAssembly模块,它在HTML5 WebGL画布上呈现一些东西。一切都正常运作。但是,为了简化该模块的使用,我希望将所有内容都封装在Web组件中。
WebAssembly模块相当大,因此需要几秒钟的时间下载。一旦下载完JavaScript模块,就会调用一个WebAssembly回调函数。
给用户一些光反馈,当模块下载在prograss中时,我会在下载模块时在画布上画一个动画。动画在回调函数中停止,模块在那里实例化。
从概念上讲,我很难将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组件。因此,我不能简单地在customElements.define回调函数中执行onModuleReady。启动动画已经太晚了。
一旦下载了模块,我就可以开始创建它的实例了。但是,我不知道如何将这些实例与通过HTML创建的Web组件实例连接起来。因为我不在表示Web组件的类之外,所以我不知道如何访问它。
是否有一种方法可以访问表示这些实例的类之外的Web实例,例如从onModuleReady内部访问
或者,更普遍地说,是否有人认为有更好的方法来处理这个问题?
发布于 2021-04-13 15:02:04
让组件侦听事件(在根级别)。
然后,onModuleReady 分派事件,该事件会出现气泡。
您可能想要一个CustomEvent:https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
请注意,您需要composed: true才能让事件“逃离”shadowRoots
从概念上讲,与标准的onload或DomContentLoaded事件没有什么不同。
备注:
details有效负载中的DataTypes。您可以添加函数引用
因此,接收器可以在分派的元素中/从分派的事件中执行方法。
synchronous处理
深入事件处理的
https://www.youtube.com/watch?v=8aGhZQkoFbQ
另见:https://pm.dartus.fr/blog/a-complete-guide-on-shadow-dom-and-event-propagation/
https://stackoverflow.com/questions/67009831
复制相似问题