KoGrid JSON Dynamic widgets, with nested server ca

2019-07-09 14:03发布

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));

标签: knockout.js
1条回答
淡お忘
2楼-- · 2019-07-09 14:23

I'm guessing you are getting this error on the data prop in the Widget class? If so, then yes it is probably the JSON structure of the data array. If they are complex objects themselves, you should repeat the same process you did for Widgets.

  1. Make an object definition for these items. Perhaps WidgetItem.
  2. use ko.utils.arrayMap to map the data array onto WidgetItem.
  3. Success.

Without seeing the structure of data though, I can't give you anything more specific.

查看更多
登录 后发表回答