Goran
Goran

Reputation: 93

Extending Knockout ViewModel with knockoutValidate results

I've played a bit with Knockout validation and now I wondering is it possible to extend Knockout so that every view model have observable with list of errors which i get from validation? In general i have

self.validationData = {
            name: ko.observable('').validateUpperEmail(),
            childName: ko.observable('').validateOther(),
            errorList: ko.observableArray([])
        };

var errors = ko.validation.group(self.validationData);

var showErrorMessages = function () {
            errors.showAllMessages(true);

            linqjs.from(errors()).distinct('$._latestValue').forEach(function(errorMessage) {
                self.validationData.errorList.push({ text: errorMessage() });
            });

        };

Question is: is there a way to populate errorList from some other place so that i can easily remove this property from every single view model and just use inherited one?

Upvotes: 1

Views: 2832

Answers (1)

Jared
Jared

Reputation: 702

You can use knockouts extend feature.

var baseModel = function() {
    var self = this;

    self.errorList = ko.observable('This is an example');
}

var childModel = function() { 
    var self = this;
    self.name = ko.observable('Test1');
    self.childName = ko.observable('');
    ko.utils.extend(self, new baseModel());

}

Here's the fiddle.

Upvotes: 2

Related Questions