I am working on a dashboard where I am using KOGrid, my idea is to dynamically create a bunch of widgets and bind data into the kogrid for each widget. I have two controllers (MVC4), where the fist returns a list of widget names and the second returns results (datatable) for each widget in JSON format. I am using JSON.Net JsonConvert to convert the results to json format then passing as JSON content result.
I am getting "Uncaught Error: The argument passed when initializing an observable array must be an array, or null, or undefined". Is it the nested JSON calls a problem? What is the most reliable way to handle Arrays of complex objects and binding them to multiple grids. Does it help if I use knockout.mapping?
var widgets = {};
var Widget = function (id, data) {
this.id = ko.observableArray(id || []);
this.data = ko.observableArray(data || []);
};
var ViewModel = function (data) {
var self = this;
self.widgets = ko.observableArray(
ko.utils.arrayMap(data, function (i) {
return new Widget(i);
}));
$.getJSON('Widgets/Get', null, function (data) {
$.each(data, function (index, item) {
$.getJSON('Home/GetWidgetDetails?widgetName=' + item.WIDGET_NAME,
function (result) {
self.widgets.push(new Widget({ id: item.WIDGET_NAME, data: result }));
});
});
});
};
ko.applyBindings(new ViewModel(widgets));
I'm guessing you are getting this error on the
data
prop in theWidget
class? If so, then yes it is probably the JSON structure of thedata
array. If they are complex objects themselves, you should repeat the same process you did for Widgets.WidgetItem
.ko.utils.arrayMap
to map thedata
array ontoWidgetItem
.Without seeing the structure of
data
though, I can't give you anything more specific.