josdejong / svelte-jsoneditor

A web-based tool to view, edit, format, repair, query, transform, and validate JSON
https://jsoneditoronline.org
Other
816 stars 108 forks source link

Get reference to editor from the html element it targets. #388

Closed bzuidgeest closed 5 months ago

bzuidgeest commented 5 months ago

This might be an obvious thing for most javascript programmers, but I'm mostly into c#. So here goes.

Is it possible to retrieve the editor instance object by means of the editor target element?

Consider the example below. There is the div "jsoneditor" and there is the const jsoneditor with an instance of the editor that also points to the target div.

Is there a way to do for example something like:

document.getElementById('jsoneditor').jsoneditorInstanceOnThisElement.Updateprops(.......), etc

This would be usefull as that way I can always get a reference to the correct instance for specific element if I have multiple editors on a single page.

<!doctype html>
<html lang="en">
  <head>
    <title>JSONEditor</title>
  </head>
  <body>
    <div id="jsoneditor"></div>

    <script type="module">
      import { JSONEditor } from 'vanilla-jsoneditor/standalone.js'

      // Or use it through a CDN (not recommended for use in production):
      // import { JSONEditor } from 'https://unpkg.com/vanilla-jsoneditor/standalone.js'
      // import { JSONEditor } from 'https://cdn.jsdelivr.net/npm/vanilla-jsoneditor/standalone.js'

      let content = {
        text: undefined,
        json: {
          greeting: 'Hello World'
        }
      }

      const editor = new JSONEditor({
        target: document.getElementById('jsoneditor'),
        props: {
          content,
          onChange: (updatedContent, previousContent, { contentErrors, patchResult }) => {
            // content is an object { json: unknown } | { text: string }
            console.log('onChange', { updatedContent, previousContent, contentErrors, patchResult })
            content = updatedContent
          }
        }
      })

      // use methods get, set, update, and onChange to get data in or out of the editor.
      // Use updateProps to update properties.
    </script>
  </body>
</html>
josdejong commented 5 months ago

You can do something like:


const target = document.getElementById('jsoneditor')
const editor = new JSONEditor({ target, ... })
target.editor = editor
bzuidgeest commented 5 months ago

Ah, I forget how flexible the dom/javascript seems to be, I can attach the editor to the target myself.

Thanks for the quick answer.

josdejong commented 5 months ago

Yes. This flexibility also makes it easy to create a mess for yourself, be careful 😅 .

bzuidgeest commented 5 months ago

I'm already learning/switching to typescript to be more carefull. It's also why I asked if such a property already existed. I will keep it in mind.