Frage

Here's a simple viewmodel:

var vm = {
        isValid1: ko.observable(false),
        isValid2: ko.observable(false),
        isValid3: ko.observable(false),
        isValid4: ko.observable(false),

        isAllValid: ko.computed(function() {
            return isValid1() && isValid2() && isValid3() && isValid4();
        });
}

When updating the isValid and setting them all to true like this:

vm.isValid1(true);
vm.isValid2(true);
vm.isValid3(true);
vm.isValid4(true);

isAllValid never seems to get updated. What am I doing wrong here?

Thanks

Nicolas

War es hilfreich?

Lösung 2

You cant use a literal like that, you have to create a constructor and initiate it like

var VM = function() {
        this.isValid1 = ko.observable(false);
        this.isValid2 = ko.observable(false);
        this.isValid3 = ko.observable(false);
        this.isValid4 = ko.observable(false);

        this.isAllValid = ko.computed(function() {
            return this.isValid1() && this.isValid2() && this.isValid3() && this.isValid4();
        }, this);
};

http://jsfiddle.net/FuuQf/

Or set the isAllValid function after the creation of the literal, but i do not think literals should be used for VMs

Andere Tipps

If you are using object literals as viewmodel you need to define your computed after the initial declaration:

var vm = {
        isValid1: ko.observable(false),
        isValid2: ko.observable(false),
        isValid3: ko.observable(false),
        isValid4: ko.observable(false)
}

vm.isAllValid = ko.computed(function() {
   return vm.isValid1() && vm.isValid2() && vm.isValid3() && vm.isValid4();
});

This is needed because the way how object literals and scoping working in javascript. Anyway it is better to use a constructor function as your view model if your view model is getting complex (like having cumputed properties etc.)

For further read: Difference between knockout View Models declared as object literals vs functions

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top