如何设置摩纳哥编辑器并更改价值?

时间:2019-02-18 23:33:37

标签: javascript monaco-editor visual-studio-monaco

我想使用monaco编辑器查看目录的不同文件。我想创建一个编辑器并动态更改内容。但这并不符合我的期望。

function doSomething(val) {
  require.config({ paths: { 'vs': 'min/vs' }});
  require(['vs/editor/editor.main'], function() {
    monEditor = monaco.editor.create(document.getElementById("content"), {
      value: val,
      language: "plain",
      scrollBeyondLastLine: false,
      readOnly: true
    });
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<link type="text/css" href="min/vs/editor/editor.main.css" rel="stylesheet">

<body>
<!--- Modal start -->
<div id="content" style="height:100px; width: 100px;"> </div> <!-- Modal content -->
<!-- Modal end -->

<button onclick="doSomething('Input1')"> Change1 </button>
<button onclick="doSomething('Input2')"> Change2 </button>

<script src="min/vs/loader.js"></script>

</body>
</html>

这是我的代码。我第一次打开模式时,一切正常,但比摩纳哥编辑消失了。

当我尝试使用monEditor.setValue(val)时,出现未定义monEditor的错误。

当我尝试使用monEditor.setModel(model)时,出现错误,表明找不到该节点。

有人知道我做错了什么,或者需要进行哪些更改才能使其正常工作?我已经尝试了很多,但是没有正确设置编辑器。 不幸的是,这些示例也无济于事,因为它们包含不在存储库中的数据。

1 个答案:

答案 0 :(得分:0)

JavaScript使用范围,它们是小的执行上下文。在范围内声明的变量可以被当前范围的子范围访问(“可见”),但不能访问任何外部范围。 (请参见the definition on the Mozilla Developer Networkthis comprehensive guide to JavaScript's scopes。)

您正在函数作用域内定义monEditor变量,这就是为什么以后无法访问它的原因。您可以按以下方式重新定义功能:

let monEditor;

function doSomething (val) {
    require.config ({ paths: { 'vs': 'min/vs' }});
    require (['vs/editor/editor.main'], function () {
        monEditor = monaco.editor.create (document.getElementById ("content"), {
          value: val,
          language: "plain",
          scrollBeyondLastLine: false,
          readOnly: true
        });
    });
}

此处monEditor在全局范围内定义,使其可用于所有功能。尝试重新声明它会引发错误,因为monEditor是用let声明的。

相关问题