0
votes

I'm using the knockout mapping plugin. The simplified json I'm getting is in the form of an unnamed array.

[
 {"ID":1,"Title":"Title 1"},
 {"ID":2,"Title":"Title 2"},
 {"ID":3,"Title":"Title 3"}
]

In order to have a named "Items" property in my viewmodel, I'm assigning like this:

var model = { Items: ko.mapping.fromJS(jsondata, mappingOptions) }  

I'm having trouble adding the isDirty property during the mapping process. I'm starting to wonder if I'm approaching this the wrong way.

Here is a JsFiddle

UPDATE

Here is a working JsFiddle based on the answer below.

1

1 Answers

1
votes

The issue you're seeing in your fiddle is that your "create" method of your mapping is not being called.

You've defined your mapping as

var mappingOptions = {
    Items: {
        create: function (mappingoptions) {            
            ...
        }
    }
};

so the ko.mapping is looking for an array property of your data object called "Items", on each item of which it will run the "create" method. However, your data object "jsn" does not have a collection named "Items".

  var jsondata = [
    {"ID":1,"Title":"Title 1"},
    {"ID":2,"Title":"Title 2"}
  ]

If you change your jsondata to be :

var jsondata = { 
    Items : [
        {"ID":1,"Title":"Title 1"},
        {"ID":2,"Title":"Title 2"}
    ]
}

you should see the "create" method execute and your isDirty flags will be added.

You could also change your mapping to eliminate the "Items" :

var mappingOptions = {
    create: function (mappingoptions) {            
        ...        
    }
};

Hope this helps!