Traiko Dinev
Traiko Dinev

Reputation: 96

Knockout computed reset on select show/hide

I recently encountered a strange behavior in knockout. To illustrate, take a look at this fiddle: http://jsfiddle.net/77aP3/ .

this.myVar = ko.observable();
    this.vars = ko.observableArray(["Dave", "Steve", "Jim"]);
    this.tf = ko.observableArray([true, false]);
    this.show = ko.observable();
    var self = this;

    this.myVarChanger = ko.computed({
        read: function () {
            return self.myVar;
        },
        write: function (value) {
            self.myVar(value);
        }
    });

When you change the value in the first select (Dave, Steve, Jim), a corresponding variable changes in the view model. The second select changes whether the first one is displayed.

Try selecting Steve or Jim in the first select and after that hide it (select false in the second select). When you show it again, the value of myVar automatically changes to Dave (the default value), instead of switching to the one you selected. This does NOT happen if you don't use a ko.computed but the pure observable instead.

Is this supposed to happen? My guess is that knockout reevaluates the computed variable when it shows the select as it usually does in the beginning of the program's execution.

Upvotes: 1

Views: 860

Answers (1)

nemesv
nemesv

Reputation: 139768

You have this "strange" behaviour because you have a "bug" in your read method. Namelly you are returning the myVar observable function itself and not its value. So your select will be reseted to "Dave" because the self.myVar function does not exists in the vars array.

So if you change your myVarChanger's read method to return self.myVar(); it will produce the expected behavior:

this.myVarChanger = ko.computed({
        read: function () {
            return self.myVar();
        },
        write: function (value) {
            self.myVar(value);
        }
    });

Demo JSFiddle.

Upvotes: 2

Related Questions