我有一个用于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>发布于 2018-07-18 08:08:58
首先,去掉处理程序之外的编辑器变量--这不是很酷。您不需要共享实例,您需要的是一个处理程序一次管理两个编辑器实例,每个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个主题和任何选项,然后在处理程序中:
https://stackoverflow.com/questions/51377853
复制相似问题