JakeP
JakeP

Reputation: 757

knockout variable not defined - scoping issue?

I have the following code:

var ObjectViewModel = function (testObject) {
    //debugger;
    var self = this;
    self.id = testSet.id;
    self.details = testOject.details;
    self.children = ko.observableArray(testObject.children);
    self.childCount = ko.computed(function() {
        return self.children().length;
    });

    self.addObject = function () {
        //debugger;
        // Pending UI
        // Call API here
        // On success, complete
        self.children.push(dummyObject);
        self.childToAdd("");
    }.bind(self);
    }
    / etc

However in childCount, this.children() is undefined. I'm trying to let the view show the length of the children array in real-time, so as the user adds/removes items, the count is updated. Any idea why this isn't working?

Upvotes: 0

Views: 390

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

You can pass what the value of this should be when the function is executed to the computed function with the last parameter:

this.childCount = ko.computed(function() {
    return this.children().length;
}, this);

You could also store a reference to this outside of the computed:

var self = this;
this.childCount = ko.computed(function () {
    return self.children().length;
});

Upvotes: 2

Related Questions