Monday, 15 February 2010

javascript - OOP approach in js with ajax -



javascript - OOP approach in js with ajax -

... hi have object:

function page(daoservice) { this.daoservice = daoservice; this.gameslist = this.daoservice.getgameslist(); } // rendering thumbs main page page.prototype.renderthumbs = function(idcontainer){ var container = document.getelementbyid(idcontainer); (var = 0; < this.gameslist.length; i++) { var thumbnode = document.createtextnode("<div class='thumbicon'></div>"); thumbnode.style.backgroundimage = const.path_thumbs + this.gameslist.gametitleseo; container.appendchild(thumbnode); } };

and have function in code uses object:

document.onreadystatechange = function() { if (document.readystate == "interactive") { // initialization of elements // setting global dao service var daoservice = ajaxservice(); // initialization page object var page = new page(daoservice); page.renderthumbs("homepagecontainer"); } }

the issue here when i'm calling page.renderthumbs, field this.gameslist still didn't initialized, because didn't ajax response server. can help me handle need alter in approach? thanks

you'll need set getgameslist on daoservice handle asynchronous method. here rough sketch of i'm meaning:

daoservice.prototype.getgameslist = function(callback) { var self = this; // has gameslist been populated previous phone call function? if (this.gameslist) { // gameslist property has values, phone call callback. callback(this.gameslist); } else { // gameslist not populated, create ajax call. $.ajax('url').done(function(data) { // handle info coming server. self.gameslist = data; callback(this.gameslist); }); } }

you can consume getgameslist method phone call renderthumbs so:

page.prototype.renderthumbs = function(idcontainer){ var container = document.getelementbyid(idcontainer); // anonymous function called whether list // populated in daoservice or ajax phone call made. this.daoservice.getgameslist(function(gameslist) { (var = 0; < gameslist.length; i++) { var thumbnode = document.createtextnode("<div class='thumbicon'></div>"); thumbnode.style.backgroundimage = const.path_thumbs + gameslist[i].gametitleseo; container.appendchild(thumbnode); } }); };

javascript ajax oop document-ready

No comments:

Post a Comment