Child collection mapping not firing

£可爱£侵袭症+ 提交于 2019-12-13 06:49:04

问题


I have used the search engine, and found alot of answers, but I am stuck on a problem. The problem is that the child collection mapping seems to not fire. In the below code the alert "Groups created", but the "Root created"-alert is shown.

var mapping = {
    'Groups': {
        create: function (options) {
            var lang = ko.observable(ko.mapping.fromJS(options.data));
            alert('Groups created');
            return lang;
        }
    },
    create: function (options) {
        var innerModel = ko.mapping.fromJS(options.data);
        alert('Root created');
        innerModel.ajaxSave = submitFormWithAjax;
        return innerModel;
    }
}

var viewModel = null;
function loadViewModel(model, offlineCache, key) {
    viewModel = ko.mapping.fromJS(model, mapping);

    if (typeof extendViewModel == 'function') {
        extendViewModel();
    }

    ko.applyBindings(viewModel);
}

and my json data looks like this

{
  "Groups": [
    {
      "Texts": [
        {
          "Language": {
            "Id": 1,
            "Name": "English",
            "Lcid": 2057
          },
          "Id": 1,
          "Value": "Display name"
        },
        {
          "Language": {
            "Id": 2,
            "Name": "Swedish",
            "Lcid": 1053
          },
          "Id": 2,
          "Value": "Visningsnamn"
        }
      ],
      "Id": 1,
      "InternalName": "3dc075e3-ff96-4044-b9bb-4a0404912866",
      "DisplayName": "Display name"
    }
  ],
  "AvailableLanguages": [
    {
      "Id": 1,
      "Name": "English",
      "Lcid": 2057
    },
    {
      "Id": 2,
      "Name": "Swedish",
      "Lcid": 1053
    }
  ]
}

Why is my Groups-created alert fired?


回答1:


You cant have create functions on more than one level for some reason with the mapping plugin, you can do this

RootViewModel = function(data) {
   this.stuffAddedToViewModelBeforeMapping = "Hej på dig";

   var mapping = {
       Groups: {
           create: function(options) {
               return new GroupViewModel(options.data);
           }
       },
       AvailableLanguages: {
           create: function(options) {
               return new LanguageViewModel(options.data);
           }
       }
   };
   ko.mapping.fromJS(data, mapping, this);
};

LanguageViewModel = function(data) {
    ko.mapping.fromJS(data, {}, this);
}

GroupViewModel = function(data) {
    ko.mapping.fromJS(data, {}, this);
};

http://jsfiddle.net/42ZwC/

Lycka till!



来源:https://stackoverflow.com/questions/24199726/child-collection-mapping-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!