0

I want to use the monaco-editor to look at different files of a directory. I want to create an editor and change the content dynamically. But it doesn't work the way I want it to.

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>

This is my code. The first time i open the modal everything works fine but than the monaco-editor disappear.

When i try to use monEditor.setValue(val) an error appear that monEditor is not defined.

And when i try to use monEditor.setModel(model) an error appear that the node is not found.

Does anyone know what I'm doing wrong or what I need to change to make it work? I've tried a lot, but I don't get the editor set up right. Unfortunately, the examples don't help me either, because they include data that is not in the repository.

UnfckJ
  • 11
  • 1
  • 1

1 Answers1

0

JavaScript uses scopes, which are small contexts of execution. Variables declared within a scope may be accessible ("visible") to sub-scopes of the current scope, but not to any outer ones. (See the definition on the Mozilla Developer Network and this comprehensive guide to JavaScript's scopes.)

You are defining your monEditor variable inside of a function scope, which is why you are not able to access it any time later. You can redefine your function as follows:

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
        });
    });
}

Here monEditor is defined on the global scope, making it available to all functions. Trying to redeclare it will throw an error because monEditor is declared with let.

Alexander Leithner
  • 3,169
  • 22
  • 33