绑定第三级映射

时间:2017-11-07 13:06:06

标签: javascript knockout.js

您好我有以下模型结构,但遗憾的是调试器从不进入第三级映射,这一切都指向我如何使用与映射链接相关的构造函数但不确定如何正确执行此操作。你能帮忙吗?

ReservationViewModel  = function (data) {
     var self = this;
     ko.mapping.fromJS(data, reservationOptionsMapping, self);
}
// 2nd level constructor
ReservationOptionsViewModel = function (data) {
     var self = this;
     ko.mapping.fromJS(data, reservationOptionsMapping, self);
}
 var reservationOptionsMapping = {
       'ReservationOptions': {
           key: function (reservationOption) {
               return ko.utils.unwrapObservable(reservationOption.Id);
           },
           create: function (options) {
              return new ReservationOptionsViewModel(options.data, 
           reservationOptionValuesMapping);
          }
       }
    }
//3nd level constructor
ReservationOptionsValuesViewModel = function (data) {
    var self = this;
    debugger
    ko.mapping.fromJS(data, reservationOptionValuesMapping, self);
}
var reservationOptionValuesMapping = {
   'ReservationOptionValues': {
       key: function (reservationOptionValues) {
            return 
ko.utils.unwrapObservable(reservationOptionValues.Id);
      },
      create: function (options) {
          return new ReservationOptionsValuesViewModel(options.data);
      }
  }
}

 var formControlsModel = new EditReservationViewModel(@Html.Raw(data));
   debugger;
   ko.cleanNode($('.modal-body')[0]);
   ko.applyBindings(formControlsModel, $('.modal-body')[0] );

我的数据结构如下所示:

var data = 
{"Id":1017,
"Title":"title1",
"LogoPath":"logo1",
"StartDate":"06/11/2017",
"EndDate":"06/11/2017",
"StartTime":"00:00",
"EndTime":"00:10",
"TimeSpan":1,
"MinPersons":2,
"MaxPersons":3,
"CompanyId":1,
"ReservationOptions":[{
    "Id":1011,
    "Title":"desc1",
    "Info":"info1",
    "TypeId":1,
    "TypeDescription":"Radio Button",
    "ReservationOptionValues":[
        {"Id":1034,"ValueTitle":"a"},
        {"Id":1035,"ValueTitle":"b"},
        {"Id":1036,"ValueTitle":"c"}],
    "NewValues":null}]};

1 个答案:

答案 0 :(得分:1)

您的第一级和第二级构造函数都使用相同的第二级映射对象。我认为您需要更改二级构造函数,以便为其子级(reservationOptionValuesMapping)使用第三级映射,然后您的第三级构造函数根本不应使用子映射。

// 1st level constructor
ReservationViewModel = function(data) {
    var self = this;
    ko.mapping.fromJS(data, reservationOptionsMapping, self);
}
// 2nd level constructor
ReservationOptionsViewModel = function (data) {
    var self = this;
    //ko.mapping.fromJS(data, reservationOptionsMapping, self);
    ko.mapping.fromJS(data, reservationOptionValuesMapping, self);
}
//3nd level constructor
ReservationOptionsValuesViewModel = function (data) {
    var self = this;
    debugger
    //ko.mapping.fromJS(data, reservationOptionValuesMapping, self);
    ko.mapping.fromJS(data, null, self);
}