我正在尝试为 wysihtml5 控件设置淘汰赛验证。目前我有以下代码:
<div>
<textarea data-bind="wysihtml5: { data: Text, options: { 'font-styles': false, 'link': false, 'image': false, 'html': true } }"></textarea>
</div>
和视图模型:
viewModel.Text.extend({ required: true });
viewModel.saveValidationGroup = ko.validatedObservable({
Text: viewModel.Text
});
viewModel.save = function () {
if (!viewModel.saveValidationGroup.isValid()) {
viewModel.saveValidationGroup.errors.showAllMessages();
return false;
} else {
console.log(ko.toJSON(viewModel.Text));
}
};
运行app时,控件正常加载,当textarea为空时,仍然设置了Text viewmodel属性:
<span id=\"_wysihtml5-undo\" class=\"_wysihtml5-temp\"></span><span><br><ul> </ul> </span>
问题是将 wysihtml5 控件与 knockout.validation 集成的正确方法是什么。
编辑:自定义绑定
ko.bindingHandlers.wysihtml5 = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var options = {};
var value = ko.utils.unwrapObservable(valueAccessor()) || {};
options.events = {
"change": function () {
var observable;
var content = ko.utils.unwrapObservable(valueAccessor()) || {};
if (content.data != undefined) {
observable = valueAccessor().data;
} else {
observable = valueAccessor();
}
observable(control.getValue());
}
};
if (value.options) {
ko.utils.extend(options, value.options);
delete value.options;
}
// if the textarea has no id, generate one to keep wysihtml5 happy
if ($(element).attr('id') == undefined || $(element).attr('id') == '')
$(element).attr('id', 'id_' + Math.floor(new Date().valueOf()));
var control = $(element).wysihtml5(options).data("wysihtml5").editor;
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
//
var control = $(element).data("wysihtml5").editor;
var content = ko.utils.unwrapObservable(valueAccessor()) || {};
if (content.data != undefined) {
control.setValue(valueAccessor().data());
} else {
control.setValue(valueAccessor()());
}
}
};
ko.validation.makeBindingHandlerValidatable('wysihtml5');