James
James

Reputation: 1945

why computed function runs automatically

I have one knockout computed function like this in my code

 self.TestFunction = ko.computed(function () {
            //Some logic
        }, self).extend({ rateLimit: 100 });

This function is executed automatically without its been binded to any html element. I would like to know the reason behind it.

Upvotes: 0

Views: 54

Answers (1)

user3297291
user3297291

Reputation: 23372

I would like to know the reason behind it

Usually, you use a ko.computed for its return value. However, this isn't their only use. Often, you'll see code using a ko.computed more like a fancy way to subscribe to multiple values. For example

// Please note, I do *not* recommend these kinds of structures, I'm merely
// showing knockout allows them
const input1 = ko.observable("");
const input2 = ko.observable("");
const input3 = ko.observable("");

ko.computed(function someSideEffect() {
  input1();
  input2();
  input3();

  console.log("Some value has changed!");
});

Now, for knockout to be able to "run" the side effect of logging to console, it has to find out what its dependencies are. It does so by running the someSideEffect function once.

As mentioned in the comments, pureComputed properties work differently. They only run their inner function once their own value is requested.

In short:

  • ko.computed runs its inner function upon creation because it supports side-effects.
  • ko.pureComputed only runs once when its value is requested, and pauses when there are no dependencies.

Upvotes: 2

Related Questions