Nikos
Nikos

Reputation: 7552

Knockouts ko.computed variable does not update when obserable is changed

How come the computed function this.followButtonText doesn't update ,always shows(Follow), when the observable this.isFollowing is changed? $(document).ready(function () {

        function AppViewModel() {

            this.toggleIsFollowing = function () {
                this.isFollowing = !this.isFollowing;
                follow();
            };

            this.isFollowing = ko.observable(false);
            this.followButtonText = ko.computed(function () {
                return this.isFollowing ? "Unfollow" : "Follow";
            });
        }

        ko.applyBindings(new AppViewModel());


        }

    });
</script>

Upvotes: 2

Views: 260

Answers (2)

Tib
Tib

Reputation: 272

Change this statement: return this.isFollowing ? "Unfollow" : "Follow";

To this: return this.isFollowing() ? "Unfollow" : "Follow";

The parenthesis calls it as a function which is needed in order to get the most current value

Upvotes: 2

RP Niemeyer
RP Niemeyer

Reputation: 114792

An observable is actually a function. To read the current value you need to call it as a function with no arguments like: this.isFollowing().

To set the value of an observable, you need to pass the new value as the first argument. So, your toggle would look like: this.isFollowing(!this.isFollowing());

In your followButtonText computed, you would need to call it as a function as well like:

return this.isFollowing() ? "Unfollow" : "Follow";

Upvotes: 2

Related Questions