dzjosjusuns
dzjosjusuns

Reputation: 111

ko.computed() does not evaluate for top level object (knockout mapping)

I have two values on page, one is ko.computed property other ko.observable, both should get same value but in two different ways (base data is loaded using ko.mapping.fromJS):

        //#1
        self.count = ko.computed(function () {
            return self.pages().length;
        });

        //#2
        self.count2 = ko.observable(0);
        ko.computed(function () {
            //looks like this is not fiering
            self.count2(self.pages().length);
        });

In my case #1 works great, but #2 fails to trigger at all. in same manner if i would use self.page.subscribe(), i would also get desired result.

And there is second part to this problem, if i create some nested objects, then case #1 and #2 work as expected for nested ones, but problem still exists on top level / parent object.

And hear is sample that demonstrates this strange behavior - http://jsfiddle.net/rrgnK/2/

I would like to know what causes this problem, is it my code / structure or something else? (there is no particular problem i'm trying to solve this way, i just noticed this strange behavior and that lead me to thought that i may be doing something fundamentally wrong)

Upvotes: 1

Views: 324

Answers (1)

Alnitak
Alnitak

Reputation: 339786

Your second .computed field isn't bound to anything, it'll never get called.

I don't have a proposed fix because that's simply not what you're supposed to do. Your first code pattern is the expected way to get read access to a variable derived from some other property.

Upvotes: 2

Related Questions