Graham
Graham

Reputation: 1517

Accessing Knockout Observable Property from Computed Property Gives TypeError

I'm sure this is probably a basic problem, but I have the following ViewModel:

var viewModel = new EditorViewModel();
viewModel.addData(model);
ko.applyBindings(viewModel);

var EditorViewModel = function () {

    var self = this;
    self.addData = function (data) { .
        ko.mapping.fromJS(data, {}, self);
    };
    self.isUpdate = ko.computed(function () { return self.id() !== "0"; }, self);

};

The ViewModel receives data via the addData method. This method then maps the received data using the Knockout Mapping Plugin. For info, this data is supplied via an external JQuery AJAX call.

The problem is that I am getting the following error in Mozilla:

TypeError: self.Id is not a function

I'm not sure why the computed property is causing this error?

Upvotes: 1

Views: 91

Answers (1)

nemesv
nemesv

Reputation: 139748

By default, when you create a ko.computed it is immediately evaluated.

So in your case the function () { return self.id() !== "0"; } runs before you call your addData method, so your id property will be missing and you get the exception.

To fix this you need to tell KO to defer the evaluation with the deferEvaluation option:

 self.isUpdate = ko.computed(
     function () { return self.id() !== "0"; }, 
     self, { deferEvaluation: true });

Upvotes: 1

Related Questions