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:
- click run in jsfidle
- click on refresh in the generated result page
- click on save it will throw 4 alert messages one containing the
- 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:
- How can I prevent the initial value from being submitted?
- What is the object that is being thrown in the alerts?
- How can I include the computed property nameLength to the submit?