json - Jquery and getJson, only works when using alert() -
i having trouble jquery. seems acting oddly. what's going on. trying obtain equation json file , evaluating knockout observable objects.
what's weird it, works when use alert('') message, without it, doesn't work.
i googled question , answers regard ajax call. im using jquery function $getjson here
code
function loaddata(filename) { var data = $.getjson( filename + ".json"); return(data); } var res = 0; var student = function(data) { var self = this; ko.mapping.fromjs(data, { }, self); var res = 0; self.result = ko.computed(function() { loaddata("eqn").done(function(data1) { if (data1 && data1.eqn) { $.each(data1.eqn, function(key, value){ var str = value.equation; res = eval (str); }); } }); return(res); }); };
everything working fine if add alert before return().
eqn.json
{ "eqn":[ { "equation":"parsefloat(self.english()) + parsefloat(self.japanese()) + parsefloat(self.calculus()) + parsefloat(self.geometry())" } ] }
data.json
{ "info":[ { "name":"noob here", "major":"language", "sex":"male", "english":"15", "japanese":"5", "calculus":"0", "geometry":"20" }, { "name":"noob here", "major":"calculus", "sex":"female", "english":"0.5", "japanese":"40", "calculus":"20", "geometry":"05" } ] }
complete code in here
edit
so main problem was, dependencies fetched json data. following workaround proved solution:
self.eqn = ko.observable(null); self.reslut = ko.computed(function(){ return self.eqn() && eval( self.eqn() ); }); loaddata("eqn").done(function(data1) { if (data1 && data1.eqn) { $.each(data1.eqn, function(key, value){ self.eqn( value.equation;); }); } });
===========================================
you cannot return asynchronous function. need set helper observable, value change in callback getjson.
right dont see why computed cant observable.
// let self.result simple observable self.result = ko.observable(); // call function update self.result loaddata("eqn").done(function(data1) { if (data1 && data1.eqn) { $.each(data1.eqn, function(key, value){ var str = value.equation; res = eval (str); // set value of self.result result of // computing function self.result( res ); }); } })
you need use ko.computed
if variable depends on ko.observable
var = ko.observable("peter"), b = ko.computed(function(){ return "hi " + (); });
in case, whenever update a, b updated. can see short hand following
var = ko.observable("peter"), b = ko.observable("hi peter"); a.subscribe(function(v){ b( "hi " + v ); });
Comments
Post a Comment