首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将WebAssembly模块包装到Web组件时出现的异步问题

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

Stack Overflow用户
提问于 2021-04-08 18:26:18
回答 1查看 371关注 0票数 1

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

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

给用户一些光反馈,当模块下载在prograss中时,我会在下载模块时在画布上画一个动画。动画在回调函数中停止,模块在那里实例化。

从概念上讲,我很难将JavaScript回调函数与表示Web组件的类结合起来。到目前为止,我的情况如下:

代码语言:javascript
复制
// 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内部访问

或者,更普遍地说,是否有人认为有更好的方法来处理这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-13 15:02:04

让组件侦听事件(在级别)。

然后,onModuleReady 分派事件,该事件会出现气泡。

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

请注意,您需要composed: true才能让事件“逃离”shadowRoots

从概念上讲,与标准的onloadDomContentLoaded事件没有什么不同。

备注:

  • 您不限于CustomEvent details有效负载中的DataTypes。

您可以添加函数引用

因此,接收器可以在分派的元素中/从分派的事件中执行方法。

synchronous处理

  • 事件

深入事件处理的

  • 参见:事件循环是什么?

https://www.youtube.com/watch?v=8aGhZQkoFbQ

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67009831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档