Warm tip: This article is reproduced from serverfault.com, please click

view does not update

发布于 2020-12-15 11:17:42

When I press the "Update" Button I see the alert with the correct value (true/false) but the class "done" wont get applied. Why does the view not update?

<div data-bind="foreach: steps">
    <div data-bind="css: {done: complete}">
        <span data-bind="text: name"></span>
        <button data-bind="click: updateStatus">Update</button>
    </div>
</div>

var viewModel = function() {
    var self = this;
    self.steps = ko.observableArray();

    loadTestData(testDataSteps);
    function loadTestData(stepsArray) {
        $.each( stepsArray, function( index, value ){
            self.steps.push(new Step(value.id, value.name, value.step))
        });
    }
}

var Step = function (id, name, step){
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
    self.step = ko.observable(step);
    self.complete = ko.observable(false);

    self.updateStatus = function () {
        if(self.complete === true) {
            alert("true")
            self.complete = false;
        }else {
            alert("false")
            self.complete = true;
        }
    };
;
Questioner
webGuy
Viewed
0
Empty Brain 2020-12-15 21:30:30

Change the getter & setter method.

var Step = function (id, name, step){
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
    self.step = ko.observable(step);
    self.complete = ko.observable(false);

    self.updateStatus = function () {
        if(self.complete() === true) { //getter
            alert("true")
            self.complete(false); //setter
        }else {
            alert("false")
            self.complete(true); //setter
        }
    };
}

var viewModel = function() {
    var self = this;
    self.steps = ko.observableArray();
    self.steps.push(new Step('ID', 'TEST', 'TEST'));
    return self;
}
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div data-bind="foreach: steps">
    <div data-bind="css: {done: complete}">
        <span data-bind="text: name"></span>
        <button data-bind="click: updateStatus">Update</button>
    </div>
</div>