我有一个JSONEditor npm包的绑定处理程序。我的程序将使用户能够比较这些面板中的两个不同的JSON文件。我的bindingHandler看起来像这样:
var editor = undefined;
ko.bindingHandlers.jsoneditor = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
const options = {
"mode" : "view"
};
const value = ko.utils.unwrapObservable(valueAccessor());
if(!editor) {
editor = new JSONEditor(element, options);
editor.set(value);
}
else if(element !== editor.container){
editor = new JSONEditor(element, options);
editor.set(value);
}
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
const options = {
"mode" : "view"
};
const value = ko.utils.unwrapObservable(valueAccessor());
if(element === editor.container){
editor.destroy();
editor = new JSONEditor(element, options);
editor.set(value);
}
else {
//editor.set(value);
editor = new JSONEditor(element, options);
editor.destroy();
}
}
};
问题是,每当我切换面板时,element
都会发生变化,并使用编辑器创建错误。
这是HTML:
<div class="jsoneditor body" id="editor-1" data-bind="jsoneditor: subject1"></div>
<div class="jsoneditor body" id="editor-2" data-bind="jsoneditor: subject2"></div>
答案 0 :(得分:1)
首先,摆脱处理程序外部的编辑器变量-不酷。 您不想要共享实例,您想要的是让一个处理程序一次管理2个编辑器实例,每个JSON文件一个
ko.bindingHandlers.jsoneditor = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
const options = {
"mode" : "view"
};
const files = valueAccessor();
const editors = [];
files.forEach(f =>{
// create a new element for each subject
// and append to dom
// attach an editor to each created element
// set your new value
var $currentElem = $('<div>');
$(element).append($currentElem);
editors.push(new JSONEditor($currentElem, options));
editors[editors.length-1].set(f);
});
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
}
};
<div class="EditorContainer" id="Editor_SmUniqueThingy" data-bind="jsoneditor: { file1: subject1, file2: subject2 }"></div>
这不是一个可行的示例,我完全省略了更新,但是这个概念是...在处理程序中传递2个主题和每个选项可能需要的任何选项,然后在处理程序中传递: