0

I am currently using virtual elements to display validation errors (there can be more than 1 per path).

<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.

Nathan
  • 31
  • 3
  • It sounds like you want a [Component](http://knockoutjs.com/documentation/component-overview.html) – Roy J Oct 12 '17 at 00:31
  • I tried a couple different approaches including templates, which ultimately would have led me to a component. None worked well. In the end, I found this working example that does what I need- foreach on a filtered array. Note this is NOT my [jsfiddle](http://jsfiddle.net/nYbpE/) – Nathan Oct 12 '17 at 02:48

1 Answers1

0

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>
TSV
  • 7,538
  • 1
  • 29
  • 37
  • Thanks TSV, but unfortunately that will not work. It only works for fields named title. I need a single component to work for all fields ('tit;e', 'description' etc.). I have come up with an alternative approach that does not use a component, but it is not much less verbose than my original code (I will post it soon). I'd still like to know how to generalize it with a component. – Nathan Oct 16 '17 at 15:03
  • @nlafratta: Why dont you remove condition for `path == "title"` from `ko if: path == "title" && type == "validation"`. After removing, that will work for all paths. – SpiderCode Nov 17 '17 at 06:00