Search code examples
knockout.jsko.observablearray

Knockout Can't Access ObservableArray from inside model


This might be pretty basic but I just can not seem to figure it out. The problem goes

I have a view model with an observable array 'self.product' and want to access it from a nested model as shown below. when I run this I get an error that product does not exist. I have not included the code but there is an ajax call that gets data and pushes it to 'product'. Also using a click binding on the function 'test' does print the value.

I though it might be a scoping issue with the 'self' but since I use the 'product' array in a foreach binding in the markup I can not just change self.product... to var product. how might I accomplish this?

var viewModel = function () {
        var self = this;
        self.product = ko.observableArray([]);
var orderItem = function (data) {
            var self = this;
            self.PlayDuration = ko.computed(function () {
                var foo  = self.product()[0].something();
                return foo;
            });

        }
self.updateTotals = function () {
            console.log(self.product()[0].something());
        }
});

Solution

  • var root = this;
    

    Add that line to the outermost viewmodel and use it in the inner viewmodels.