10

I'm running into an issue with KnockoutJS's mapping plugin where I need to do the following:

  1. Customize the mapping creation of an object
  2. Customize the mapping creation of an array of nested objects from #1.

In this fiddle example I am trying have the children properly mapped to their custom creation. The expected result is that each of the children have the added description property. From the fiddle, the result should read:

  • Adam Smith
  • Bob is 5 years old
  • Chris is 7 years old

I can demonstrate the expected behaviour in this this fiddle example. Notice that in this code I must have two data sets, with the first having an empty array of children objects. The following line of code will cause the customized creation of child objects:

ko.mapping.fromJS(additionalData, parentMapping, viewModel);

Unfortunately, this requires both having empty initial children and mapping twice. This is not acceptable as the code in reality has a much deeper hierarchy.

In addition to the above, I've tried adding the following code in the parentMapping:

var mapping = { 'ignore': ["children"] };
var innerModel = ko.mapping.fromJS(options.data, mapping);
//for brevity
innerModel.children = ko.mapping.fromJS(options.data.children, childMapping);

This has the effect of mapping the children objects on the initial mapping. However, all subsequent mappings the children property is ignored.

Is there a way to customize the creation of both a parent and child object with Knockout Mapping?

Thank you.

1

1 Answer 1

18

http://jsfiddle.net/5cfa3/23/

var viewModel = {};

var data = {
  id: "1",
  firstName: 'Adam',
  lastName: "Smith",
  children: [ {id: "2", name: "Bob", age: 5}, {id: "3", name: "Chris", age: 7 }]
};

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

var mapping = {
  create:function(options){
    var parent = new Parent(options.data);
    parent.fullName = ko.computed(function(){
        return parent.firstName() + " " + parent.lastName();
    });
    return parent;
  },
  'children': {
     create: function(options) {
         options.data.description = ko.computed(function(){
             return options.data.name + " is " + options.data.age + " years old ";
         });
         return ko.mapping.fromJS(options.data);         
     }
   }
};

viewModel = ko.mapping.fromJS(data, mapping);

ko.applyBindings(viewModel);
Sign up to request clarification or add additional context in comments.

1 Comment

I updated the JSFiddle: jsfiddle.net/an40fp6y The one posted by Darussian six years ago isn't working due to https issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.