所以我尝试将 CKEditor 的内联编辑与 Knockout.js 集成。我能够成功加载 CKEditor 和 knockout.js。
我似乎无法让 ko.observable 更新属性:
<script type="text/javascript">
var viewModel = function () {
var self = this;
self.editorText = ko.observable('ABC');
self.testNewValue = function () {
console.log(this.editorText());
};
}
ko.applyBindings(new viewModel());
</script>
这是 html:
<div id="editable" contenteditable="true" data-bind="html: editorText">
</div>
<div>
<input type="button" data-bind="click: testNewValue" value="test" />
</div>
无论您是否更新,console.log 结果始终显示“ABC”。注意:我还尝试了 data-bind="text: editorText"
最佳答案
您必须编写自定义绑定(bind)处理程序,以便将您的可观察属性与 CKEditor 实例链接。
首先,您可以从找到的自定义绑定(bind) here 开始。其中一篇文章包含自定义绑定(bind),但我不确定它是否有效。你必须检查一下。我把它复制在这里,当然,学分不会归我:
ko.bindingHandlers.ckEditor = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var txtBoxID = $(element).attr("id");
var options = allBindingsAccessor().richTextOptions || {};
options.toolbar_Full = [
['Source', '-', 'Format', 'Font', 'FontSize', 'TextColor', 'BGColor', '-', 'Bold', 'Italic', 'Underline', 'SpellChecker'],
['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl'],
['Link', 'Unlink', 'Image', 'Table']
];
// handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
if (CKEDITOR.instances[txtBoxID]){
CKEDITOR.remove(CKEDITOR.instances[txtBoxID]);
}
});
$(element).ckeditor(options);
// wire up the blur event to ensure our observable is properly updated
CKEDITOR.instances[txtBoxID].focusManager.blur = function () {
var observable = valueAccessor();
observable($(element).val());
};
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var val = ko.utils.unwrapObservable(valueAccessor());
$(element).val(val);
}
}
典型的用法是在 HTML 中:
<textarea id="txt_viewModelVariableName"
data-bind="ckEditor: viewModelVariableName"></textarea>
其次,您可以查看 custom binding handler for TinyMCE最初由 Ryan Niemeyer 编写,并由其他才华横溢的人更新。也许TinyMCE可以代替 CKEditor 为你工作吗?
关于jquery - CKEditor 与 knockoutjs 内联集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16284447/