Question

I use the Knockout-Validation framework to validate the viewModel.

I have a viewmodel defined following:

ko.validation.init({
    decorateElement:true,
    errorElementClass: 'invalid',
    insertMessages: false
});

var viewModel = ko.validatedObservable({
    propety1: ko.observable().extend({ required: true }),
    propety2: ko.computed(function () {
        return this.propety1();
    }, this),
    form_onsubmit: function(form) {
        console.log(this.propety1());
        return false;
    }
});


$(function () {
    ko.applyBindings(viewModel);
});

it can get the property1's value in the form_onsubmit function, but it does't not work in the computed property "property2".

how to solve it, thanks!!!!!!!!!

Était-ce utile?

La solution

When using object literals you need to define your computed properties separately:

var viewModel = ko.validatedObservable({
    propety1: ko.observable().extend({ required: true }),    
    form_onsubmit: function(form) {
        console.log(this.propety1());
        return false;
    }
});
viewModel().propety2 = ko.computed(function () {
        return this.propety1();
}, viewModel());

Simply passing this as the second argument is not enough because it will refer to the global window object and not the object literal itself.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top