1
votes

I have the following viewModel (cut down of course):

function viewModel(calendarData) {
            var self = this;

            if (calendarData != null) {              
                self.Calendars = ko.observableArray(ko.mapping.fromJS(calendarData));                
            } else {                
                self.Calendars = ko.observableArray();
            }
}

This is my json being returned from my web api:

[{"Id":17,"Name":"try now","Events":[],"UserId":null},
 {"Id":19,"Name":"go","Events":[],"UserId":null}]

However I'm getting :

Error:

The argument passed when initializing an observable array must be an array, or null, or undefined.

I'm new to knockout so would appreciate some guidance on what I'm doing wrong here.

1

1 Answers

3
votes

ko.mapping.fromJS function makes object an observable. So ko.mapping.fromJS returns the function. But you should pass an array to ko.observableArray.
So you should use:

if (calendarData != null) {              
    self.Calendars = ko.observableArray(calendarData); // <-------                
} else {                
    self.Calendars = ko.observableArray();
}  

Or

if (calendarData != null) {              
    self.Calendars = ko.mapping.fromJS(calendarData); // <-------                
} else {                
    self.Calendars = ko.observableArray();
}