[英]Custom knockout binding to display error messages
I am currently using virtual elements to display validation errors (there can be more than 1 per path). 我目前正在使用虚拟元素来显示验证错误(每个路径可能超过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>
An example error that will be consumed by this is: 一个示例错误将被消耗:
{
path: 'title',
type: 'validation',
message: 'Title is required'
}
How can I achieve the same thing using a custom binding? 如何使用自定义绑定实现同一目的? I can't seem to find an intelligible example close enough to what I'm doing to be of any use.
我似乎找不到一个与我正在做的事情相去甚远的可理解示例。
Simple wrapped it to the component: 简单地将其包装到组件中:
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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <errors params="errors: errorsFromModel"></errors>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.