我目前正在使用虚拟元素来显示验证错误(每个路径可能超过1个)。
<div data-bind="foreach: validationErrors">
<!-- ko if: path == 'title' && type == 'validation' -->
<div class="field-validation-error text-danger" data-bind="text: message"></div>
<!-- /ko -->
</div>
此消耗的示例错误是:
{
path: 'title',
type: 'validation',
message: 'Title is required'
}
如何使用自定义绑定实现相同的功能?我似乎找不到一个可理解的例子,足够接近我正在做的任何用途。
答案 0 :(得分:0)
简单地将其包装到组件中:
ko.components.register('errors', {
viewModel: function(params) {
this.validationErrors = params.errors;
},
template:
'<div data-bind="foreach: validationErrors">\
<!-- ko if: path == "title" && type == "validation" -->\
<div class="field-validation-error text-danger" data-bind="text: message"></div>\
<!-- /ko -->\
</div>'
});
var model = {
errorsFromModel: ko.observableArray([
{path: 'title', type: 'validation', message: 'Title is required'}
])
};
ko.applyBindings(model);
setTimeout(function() { model.errorsFromModel.push({path: 'title', type: 'validation', message: 'Another error added after 1 sec'}) }, 1000);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<errors params="errors: errorsFromModel"></errors>
&#13;