0
votes

I am using knockoutjs mapping plugin. I am binding the data to viewmodel using the plugin. Then I modify the data and submit it back. While submitting I am getting the initial value of the view model and the changed value.

the fiddle is here: http://jsfiddle.net/jarajesh/HV7g4/3/

   // Here's my data model
var ViewModel = function (data) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);

    self.nameLength = ko.computed(function() {
      return self.firstName().length;
    }, self);
    self.finalstring = ko.observable('');
    self.numberOfClicks = ko.observable(0);
       self.incrementClickCounter = function() {
           var previousCount = self.numberOfClicks();
            self.numberOfClicks(previousCount + 1);
        };

       self.refresh = function() {
           var newData = {'firstName': 'refreshed', 'lastName': 'person'};
           ko.applyBindings(new ViewModel(newData));
        };

    self.save = function () {
        alert(ko.mapping.toJSON(self));
        //$.ajax({
          //  url: "Knockout2/Save",
            //type: "post",
            //contentType: "application/json",
            //data: ko.mapping.toJSON(self),
            //success: function (response) {
              //  alert(response.Status);
            //}
        //});
        //self.finalstring=ko.mapping.toJSON(self);
    };
};

var newData = {'firstName': 'first', 'lastName': 'person'};
ko.applyBindings(new ViewModel(newData));

Steps to reproduce:

  1. click run in jsfidle
  2. click on refresh in the generated result page
  3. click on save it will throw 4 alert messages one containing the
  4. initial value supplied and one with the modified value and some object :-)

I think it has something to do with the _destroy provided in the documentation.

Required solution:

  1. How can I prevent the initial value from being submitted?
  2. What is the object that is being thrown in the alerts?
  3. How can I include the computed property nameLength to the submit?
1

1 Answers

1
votes

Yikes under 5 mins of posting the question I got the answers myself

Required solution:

  1. How can I prevent the initial value from being submitted? I was applying the data again which made this happen. have modified the code as

    ko.mapping.fromJS(newData, {}, self);
    
  2. What is the object that is being thrown in the alerts?

    Was including the undefined object data in the code. modified the code as

    alert(ko.mapping.toJSON(self, mapping));
    
  3. How can I include the computed property nameLength to the submit?

    var mapping = { 'include': ["nameLength"]};
    

The updated fiddle can be found here