Closed ylaizet closed 10 months ago
To use two-way binding you'll need a framework like Svelte. There is an example of that here.
In the vanilla version, you basically listen for changes via onChange
, and you can apply changes via for example via the method editor.update(updatedContent)
. Is that what you mean?
Thanks for the tip, I tried via onChange
based on the Plain JavaScript example in the README and I managed to get bidirectional binding (two-ways) between the content of my textarea and the jsoneditor.
Here is the code. Thanks.
<!DOCTYPE html>
<html lang="en">
<head>
<title>svelte-jsoneditor demo</title>
<style>
#jsoneditor {
width: 500px;
height: 300px;
}
#json_config {
width: 500px;
height: 300px;
}
</style>
</head>
<body>
<textarea id="json_config"></textarea>
<div id="jsoneditor"></div>
<script type="module">
import { JSONEditor } from 'https://cdn.jsdelivr.net/npm/vanilla-jsoneditor/index.js'
let content = {
text: undefined,
json: {
greeting: 'Hello_World'
}
}
function updateTextarea(updatedContent) {
console.log('updateTextarea', updatedContent.json);
if (updatedContent.json !== undefined) {
let obj = document.getElementById("json_config");
obj.value = JSON.stringify(updatedContent.json, null, 2);
}
}
const editor = new JSONEditor({
target: document.getElementById('jsoneditor'),
props: {
content,
onChange: (updatedContent, previousContent, { contentErrors, patchResult }) => {
console.log('onChange', { updatedContent, previousContent, contentErrors, patchResult })
updateTextarea(updatedContent);
}
}
})
let obj = document.getElementById("json_config");
obj.value = JSON.stringify(editor.get().json, null, 2);
obj.addEventListener(
'change',
function () { editor.update({ text: this.value }) },
false
);
</script>
</body>
</html>
Thanks for sharing!
Hi, with the former jsoneditor, I used to have a two-ways binding on the content of a textarea. I tried to do it with svelte-jsoneditor without success. Is it possible? If so, could you give an example based on your vanilla javascript example using textarea in place of div. Thanks for the help or any hint.