我有一个 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>
首先,摆脱处理程序外部的编辑器变量 - 不酷。您不想要共享实例,您想要的是让处理程序一次管理 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 个主题和每个可能需要的任何选项,然后在处理程序内部:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句