javascript - Load content before call a function -
i started practice code in asynchronous programming. , i'm little bit confused, why not application working correctly.
i'm trying load json data in var jsonitems. load sound, , play.
function getjitems(jsonitems, callback){ $.getjson( "data.json", function( data ) { jsonitems.push(data); }); callback(jsonitems); } var si = []; function loadsoundjson(jsonitems){ (it =0 ; < jsonitems[0].length ; it++){ si[it] = new buzz.sound( "data/"+jsonitems[0][it].filesound, { formats: [ "ogg", "mp3"] }); } };
this how try call.
$( document ).ready(function() { getjitems(jsonitems,loadsoundjson); });
the error is: jsonitems[0] undefined
if write, works fine.
$( document ).ready(function() { getjitems(jsonitems); window.alert("forced pause"); loadsoundjson(jsonitems); });
so, want sure, whole content (images, sound, data) loaded , ready before application starts.
maybe want is, know how implement correct way making loading page. in advance.
try this:
function getjitems(jsonitems, callback){ $.getjson( "data.json", function( data ) { jsonitems.push(data); callback(jsonitems); }); }
you not calling callback @ right moment. getjson async hence when data available pushed jsonitems. @ first callback(jsonitems);
being executed before data available.
what doing @ first place execute getjitems()
ajax call (without waiting reply) call callback
Comments
Post a Comment