1
votes

I am trying to insert and update data in a knockoutjs viewmodel using the mapping plugin.
Initial data looks like (numbers are mapped in "id" field and text in "name" filed):

  • 1 one
    • 2 two
      • 3 three
      • 4 four
    • 5 five
      • 6 six
      • 7 seven
  • 8 eight
    • 9 nine
      • 10 ten
      • 11 eleven
    • 12 twelve
      • 13 thirteen
      • 14 fourteen
  • 15 fifteen

what I get is

  • 1 oneMOD
    • 2 two
      • 3 three
      • 4 four
  • 16 sixteen

what i'd like to get is:

  • 1 oneMOD
    • 2 two
      • 3 three
      • 4 four
  • 8 eight
    • 9 nine
      • 10 ten
      • 11 eleven
    • 12 twelve
      • 13 thirteen
      • 14 fourteen
  • 15 fifteen
  • 16 sixteen

in other words:

  • an update to the element 1 in field "name" from "one" to "oneMOD" (as the field id is mapped as key)
  • 5 and its son deleted (or untouched)
  • 8 and 15 untouched
  • 16 added.

It looks like ko.mapping.fromJS replaces new data instead of update them.
For sure I am missing something.

You can find the code here: http://jsbin.com/uwihoz/2/edit

TIA
Gianni

EDIT:

Ok, I misunderstood what is intended for "update" using ko.mapping.fromJS.
If you want to update your model you have to send the full original dataset with updates in it.
If you want partial updates, you have to implent it.
I'm going to test KnockoutJS-Mapping-updateData.

This post (knockoutjs-using-updatefromjs-replacing-values-when-it-should-be-adding) gave me a confirmation to my doubts.

I hope this will be helpful.

Bye,
Gianni

1

1 Answers

0
votes

In your original question, ko.mapping works by creating a NEW viewmodel. So when you so the mapping the second time, you are replacing the previous view model. Updating does basically the same thing.

What you are asking mapping to do is to understand your data and automatically update existing records and add new records. It's not that smart. You are going to have to write code that reads the update results and update/add the correct records in your original viewmodel.