# 如何在 VanillaJS 中访问跟踪的变量？

**URL:** <https://meta.discourse.org/t/access-tracked-variables-in-vanillajs/354313>\
**Category:** Development\
**Created:** [2025年二月25日 05:17 UTC](https://meta.discourse.org/t/access-tracked-variables-in-vanillajs/354313 "2025-02-25T05:17:21Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![NateDhaliwal](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/natedhaliwal/32/313494_2.png) [@NateDhaliwal](https://meta.discourse.org/u/NateDhaliwal)\
**Post date:** [2025年二月25日 05:17 UTC](https://meta.discourse.org/t/access-tracked-variables-in-vanillajs/354313/1 "2025-02-25T05:17:21Z")

</div>

我有这段代码：

```js
let iFrame = document.getElementById('oc-editor');
iFrame.addEventListener('load', function() {
  iFrame.contentWindow.postMessage({
    eventType: 'populateCode',
    language: "{{this.codeLang}}",
    files: [{
      "name": "file.{{this.codeLang}}",
      "content": "{{this.codeLang}}"
    }]
  }, "*");
});

```

它会更改 DModal 中的 iframe 以包含代码的语言和内容。但是，它告诉我 `iFrame` 是 `null`，因此无法向其添加 `addEventListener`。  
我试过这个：

```html
<template>
  <DButton @translatedLabel="Show Modal" @action={{this.showModal}} />

  {{#if this.modalIsVisible}}
    <DModal @title="Code Compiler" @closeModal={{this.hideModal}}>
      <p>Code: {{this.getCode}}</p>
      <iframe
       frameBorder="0"
       height="450px"
       src="https://onecompiler.com/embed/{{this.codeLang}}"
       width="100%"
       id="oc-editor"
       title="OneCompiler Code Editor"
       listenToEvents="true">
      </iframe>
      <script>
        let iFrame = document.getElementById('oc-editor');
        iFrame.addEventListener('load', function() {
          iFrame.contentWindow.postMessage({
            eventType: 'populateCode',
            language: "{{this.codeLang}}",
            files: [{
              "name": "file.{{this.codeLang}}",
              "content": "{{this.codeLang}}"
            }]
          }, "*");
        });
      </script>
    </DModal>
  {{/if}}
</template>

```

但这也不起作用。有什么办法可以做到吗？

* * *

仓库链接：

> **[GitHub - NateDhaliwal/Discourse-OneCompiler-Code-Runner](https://github.com/NateDhaliwal/Discourse-OneCompiler-Code-Runner)**
>
> Contribute to NateDhaliwal/Discourse-OneCompiler-Code-Runner development by creating an account on GitHub.

---

_[View the full topic](https://meta.discourse.org/t/access-tracked-variables-in-vanillajs/354313)._
