How to initialize view mode by knockout when bootstrap in view mode is empty

I use Knockout to implement a course list selection tool. I use the approach below to populate the data (MVC3 / Razor), so when the view model is first populated for the first time, I have no problem with every KO array (e.g. CourseList, ScheduleList). However, when the boot from the server returns zero lines, which means that the viewmodel 'ScheduleList' property is empty, then it is not possible to call any methods such as .push () or .removeAll (). Presumably this means that the observed array was never created, since there was nothing to fill it with. When the model is full, the ScheduleList property is populated with a list. What is the best way to instantiate when an MVC action returns it as empty? There is jsFiddle that seems to be accessing it, but when I try to use the "create" parameter, it displays my whole model empty. I'm not sure what the syntax of the "create" option is. JsFiddle is here: http://jsfiddle.net/rniemeyer/WQGVC/

// Get the data from the server var DataFromServer = @Html.Raw(Json.Encode(Model)); // Data property in viewmodel var data = { "CourseList": DataFromServer.CourseList , "ScheduleList": DataFromServer.ScheduleList }; $(function() { // Populate Data property viewModel.Data = ko.mapping.fromJS(data); // ko.applyBindings(viewModel, mappingOptions); ko.applyBindings(viewModel); }); 

When the initial loading of the page does not fill out the ScheduleList, then the following code throws an error. If the original page load contains data, you can call .removeAll () and .push (), etc.

 var oneA= 'abc'; // push not working this.Data.ScheduleList.push( oneA ); 
+7
source share
2 answers

Adjust your mapping options to make it look like a creature, you give it a specific structure. He will then make updates for you.

Most likely, your DataFromServer does not actually contain the ScheduleList property. Therefore, when it is displayed, the corresponding property is never created. Mapper will only map existing properties to observables.

You need to specify in the create parameters that the view model adds empty arrays when no array is specified. That way your view model will have corresponding observable arrays.

By ensuring that the CourseList or ScheduleList is an array, the displayed model will display them as observableArray objects so that your code works as you would expect.

 var DataFromServer = { 'CourseList': [1,2,3] //, 'ScheduleList': [] }; var dataMappingOptions = { 'create': function (options) { var data = options.data; data.CourseList = data.CourseList || []; data.ScheduleList = data.ScheduleList || []; return ko.mapping.fromJS(data); } }; viewModel.Data = ko.mapping.fromJS(DataFromServer, dataMappingOptions); 
+9
source
 var data = { CourseList: DataFromServer.CourseList || ko.observableArray([]) , ScheduleList: DataFromServer.ScheduleList || ko.observableArray([]) }; 
+1
source