asp.net mvc 3 - Is it possible to set a Knockout dependent observable with AJAX POST -
using knockout 2.0 , mvc3 razor forms, not able make dependent observable work when introduce ajax method. have set set of observables part of calculation, , when return product of observables, able set span tag correct result. however, when try use ajax method handle observables , return result, unpredictable behavior. first, appears ajax post not pick 1 of observables when input fields updated (var b posts action method 0, updated), , seems not able set result when evaluates correctly. appears there timing issue either observables or ajax call. although keeping performing calculation in javascript works fine, intent call ajax methods more complicated logic. have removed call ko.applybindings doc.ready(), , moved script methods bottom of page- way found make partly functional. viewmodel set follows:
var viewmodel = { a: ko.observable(0), b: ko.observable(1), c: ko.observable(2), // commented out, since // dependent observable handle // d: ko.observable(0) };
in dependent observable:
viewmodel.d = ko.dependentobservable(function () { var theresult = 0; $('.thelabel').css("visibility", "visible"); theresult=viewmodel.a() * viewmodel.b() * viewmodel.c(); // if return here valid result return (theresult); // prefer call ajax method // first check ensure 1 variable set if (viewmodel.a() > 0) { $.ajax("/mycalculation/getresult", { data: ko.tojson(viewmodel), type: "post", context: viewmodel, contenttype: "application/json", success: function (result) { // can't set visibility here $('.thelabel').css("visibility", "visible"); // post not pick observables, or // not set dependent observable @ return result; } }); } });
there quite bit wrong function have setup.
1.) returning function before making ajax call. code after return statement never execute.
2.) if omit first return statement, ajax call asynchronous... means execute in background , return control outer scope immediately. since don't have return statement, going return undefined.
3.) comment in success callback suggests expecting return statement propagate way computed observable. that return statement scoped callback, , not outer observable. return value used jquery, , observable long since have returned.
if want observable call ajax function need seperate value store results of asynchronous call.
here simplified example:
var viewmodel = function(){ var $this = this; $this.a = ko.observable(); $this.b = ko.observable(); $this.results = ko.observable(); //no need assign computed observable variable // because results stored in '$this.results' // need handle automatic updates ko.computed(function(){ var data = { a: $this.a(), b: $this.b() }; $.post("/do/some/stuff", data, function(results){ $this.results(results); }); }); };
Comments
Post a Comment