jquery - knockout update observable on ajax success function without reloading -
i using knockout in mvc 4application view model binding. need update view model fields on ajax success function without reloading whole view model. using following code update view model fields. issue on update of each view model filed value, whole viewmodel reloaded ends in circular request of calling updatehiddenelements method.
here view model
function viewmodel(data) { var self = this; self.fields = ko.observablearray(ko.utils.arraymap(data, function(item) { return new formfield(item); })); self.hiddenelements = ko.observablearray([]); self.dirtyflag = new ko.dirtyflag(self, false); self.applyupdates = ko.computed(function () { if (self.dirtyflag.isdirty()) { //alert("yes !!!"); updatehiddenelements(self); settimeout(function() { self.dirtyflag.reset(); }, 0); } }); }; here update method,
var updatehiddenelements = function (viewmodel) { //alert("posting data:\n\n"+ko.tojson(viewmodel)); //console.log("#### sending ajax request fetch list of elements blankout ####\n"); $.ajax({ type: "post", url: '@url.action("getblankoutelements", "offer")' + "?offerid=" + @model.id, contenttype: 'application/json; charset=utf-8', datatype: 'json', data: ko.tojson(viewmodel), success: function(result) { result.split(',').foreach(function(name) { var param = ko.utils.arrayfirst(viewmodel.fields(), function(currentparam) { return currentparam.name() == name; }); if (param) { param.value(param.default()); } }); viewmodel.hiddenelements(result.split(',')); } }); }; can suggests me how resolve issue?
i don't see how whole viewmodel can reloaded. don't understand why updatehiddenelements function not implemented directly inside viewmodel. seem me more logical , think might clear problems. 'success' functions work directly on viewmodel , don't have pass whole viewmodel around.
function viewmodel(data) { ... updatehiddenelements = function () { $.ajax({ type: "post", url: '@url.action("getblankoutelements", "offer")' + "?offerid=" + @model.id, contenttype: 'application/json; charset=utf-8', datatype: 'json', data: ko.tojson(self), success: function(result) { result.split(',').foreach(function(name) { var param = ko.utils.arrayfirst(self.fields(), function(currentparam) self.hiddenelements(result.split(',')); } ... }); }); }
Comments
Post a Comment