Object-oriented programming (OOP) implementation with asynchronous JavaScript and XML (

... I'm currently facing a situation where I have an object:

function Page(daoService) {
    this.daoService = daoService;
    this.gamesList = this.daoService.getGamesList();
}

// Rendering thumbs for main page
Page.prototype.renderThumbs = function(idContainer){
    var container = document.getElementById(idContainer);
    for (var i = 0; i < this.gamesList.length; i++) {
        var thumbNode = document.createTextNode("<div class='thumbIcon'></div>");
        thumbNode.style.backgroundImage = Const.PATH_THUMBS + this.gamesList.gameTitleseo;
        container.appendChild(thumbNode);
    }
};

In addition, there is a function in my code that utilizes the aforementioned object:

document.onreadystatechange = function() { 
    if (document.readyState == "interactive") { 
        // Initialization of elements
        // Setting global dao service
        var daoService = AjaxService();

        // Initialization for page object
        var page = new Page(daoService);
        page.renderThumbs("homePageContainer");
    } 
} 

The problem I am encountering is that when I call page.renderThumbs, the field this.gamesList has not yet been initialized as it is waiting for an ajax response from the server. Can someone provide guidance on how to address this issue and suggest any necessary changes to my approach? Thank you.

Answer №1

To effectively handle an asynchronous method, it is necessary to configure the getGamesList on daoService. Here is a basic outline of what needs to be done:

DaoService.prototype.getGamesList = function(callback) {

    var self = this;

    // Check if gamesList has already been populated by a previous call
    if (this.gamesList) {
        // If values exist in gamesList property, execute the callback.
        callback(this.gamesList);
    }
    else {
        // If gamesList is empty, initiate the ajax call.
        $.ajax('URL').done(function(data) {
            // Process the data received from the server.
            self.gamesList = data;
            callback(this.gamesList);
        });
    }


}

You can then utilize the getGamesList method within renderThumbs in the following manner:

Page.prototype.renderThumbs = function(idContainer){
    var container = document.getElementById(idContainer);

    // The anonymous function will be invoked regardless of whether the list was
    // already populated in daoService or an ajax call is triggered.
    this.daoService.getGamesList(function(gamesList) {
        for (var i = 0; i < gamesList.length; i++) {
            var thumbNode = document.createTextNode("<div class='thumbIcon'></div>");
            thumbNode.style.backgroundImage = Const.PATH_THUMBS + gamesList[i].gameTitleseo;
            container.appendChild(thumbNode);
        }
    });
};

Answer №2

Implement promises within your daoService to handle asynchronous results effectively. jQuery offers a reliable promise framework for this purpose. Symbolic representation:

function DaoService() {
   this.getGamesList = function() {
       return $.Deferred(function(defer) {
            //Perform an ajax request here and wait for the callback/complete
            //Replace DoAjax with your own ajax function or preferably use jQuery ajax, which supports promises
            DoAjax(function onReady(result) {
                defer.resolve(result.data);    
            });

       }).promise();
   }
}

In your page class, whenever you require the games list, utilize the following method. It ensures that data is only downloaded once, subsequently using the already retrieved information.

Page.prototype.renderThumbs = function(idContainer){
    var container = document.getElementById(idContainer);
    this.daoService.getGamesList().then(function(gamesList) {
       for (var i = 0; i < gamesList.length; i++) {
          var gameListItem = gamesList[i];
          //Perform necessary HTML concatenations or consider using templating options
       });
    });
    }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure bidirectional text appears correctly when two conflicting languages are combined, ensuring explicit directionality is set?

As I work on localization implementation, I encounter an issue with the directionality of mixed characters on the page. The text content is stored in a json file and inserted into the DOM using a Vue.js template. While individual characters display corre ...

Is there a method to achieve greater accuracy when dividing a large number?

My requirement involves operating on Big Numbers, and I need the results to maintain precision, as demonstrated below: const BN = require('bn.js'); var a = 11060622312717714974 var b = 1570481433500000000000; console.log(a/b); //0.00704282271460 ...

Verify whether a particular font is installed on the system

Is there a way to use JavaScript or jQuery to check if a user has Proxima Nova font installed when using Typekit? If so, I would like to incorporate that feature and then utilize jQuery to remove the Typekit loading class in order to optimize page loading ...

Deactivating one div's class upon clicking on another div

Below is the HTML code snippet: <div class="container"> <ul class="navbar"> <li class="nb-link"><a>Home</a></li> <li class="dropdown"> <a>CBSE</a> <ul class="dropdown-menu"&g ...

JavaScript encountered an issue while parsing XML: the format is not well-formed

I keep seeing an error message saying "Error parsing XML: not well-formed" when I encounter this line in my javascript code: for (var i=1; i<=totalImgs; i++) If I remove the < character from the line, the parsing error goes away. However, the javas ...

Creating a dynamic cascading dropdown list with Vue.js: Step-by-step guide

I successfully implemented a dropdown list using Vue.js, but now I want to add another similar list. How can I set this up? Here are the codes for both dropdown lists: var addUserVue = new Vue({ el: "#app", data: { heading: "Vue Select Cas ...

The children component is not recognizing the function being passed through this.props.children, resulting in an

Looking for a solution that involves passing a function to this.props.children? Check out the code snippet below: updateBarTitle(barTItle){ this.setState({barTItle}); } render(){ const children = React.Children.map(this.props.children, function (chi ...

Troubleshooting AngularJS application by Manipulating List Items

Having trouble debugging Angular lately. It feels like things are breaking and fixing themselves magically. For instance, I had an ajax call to delete a "site" which was working fine until I decided to add some code to remove it from the list as well. Now, ...

Is it possible to display a React Component code within a <code> tag?

I am in the process of creating a tester page that allows users to interact with a library component and document how it is being used. Here is the library component: render = () => { let component = ( <Slider onSlid ...

What is the process for setting up a "Highlight tab" feature in Next.Js?

I am currently working on implementing a selected tab feature in Next.Js. Users will have the ability to search for either Users or Posts by clicking on corresponding buttons. https://i.sstatic.net/mRBgQ.png Once the user clicks on a button, it should ch ...

Issue with UI not updating when calling parent controller function from mdDialog

Hey there, I'm experiencing an issue with displaying a mdDialog from Angular Material. I'm using my directive's controller as the controller for the dialog to easily call a specific function without needing to pass additional data back and a ...

Saving and accessing AJAX XML responses in sessionStorage

I have encountered an issue with storing XML response from ajax into sessionStorage. Despite successfully setting the data, I am unable to retrieve it. $.ajax({ url: '/webservice.svc/getProfile', data: { "memberId": $(authenticat ...

What is the best way to combine two elements with Mongoose?

I am in need of a mongoose query that can utilize the group feature to tally up the elements in either the STARTED or NOT INITIATED state, and then display the count of elements for each state. Shown below is the json object I am currently working with: [ ...

What is the most effective method for verifying a selected item in Jquery UI selectable?

I'm having an issue with my image display div where users can delete selected images. The code functions correctly, but there seems to be unnecessary repetition in certain parts of it. I attempted using `$(".ui-selected").each()` to stop the ...

The code snippet $(this).nextAll("#...").eq(0).text("***") isn't functioning as expected

I am experiencing an issue with the following line of code: $(this).nextAll("#status").eq(0).text("Deleted"). I am trying to insert the text "Deleted" in a <span> tag, but it does not seem to be working... Here is my code: admin.php PHP: $sql = "SE ...

Swapping out pages with JSON outcomes is a common practice when utilizing ASP.Net MVC in conjunction with JQuery Ajax

When making an ajax call to update an entity and returning the success state in the MVC controller, I encountered a problem that resulted in the page changing with the URL becoming that of the MVC controller action and displaying the JSON result as content ...

Sending output from javascript back to html

<head> function displayProductName(name) { } </head> <body> <img src="...images/car.jpg" onclick="displayProductName('car')"> </body> How can I modify this javascript function to display the value received from t ...

invalid audio element

I'm currently working on building an audio player with a visualizer feature. However, when I try to initiate the audio player by clicking on the input button, my debug console keeps showing this error message: Uncaught (in promise) DOMException: Fa ...

Avoiding the hashtag symbol in a serialized string

I have a serialized string that I am sending to the server, structured like this: counter=1&Id=4&type=2332&amount=3232&gstIncluded=3232&paymentMethod=2&notes=2332#fdsf&docId=0&ref=3232&isEdit=true The issue I am encoun ...

PHP strtotime is adding an extra hour to my time

Within my database table, I have a datetime stored as '2014-08-05 15:12:00'. After using strtotime() to convert this date to milliseconds, on the client side I create a new Date object as follows: var date = new Date(date_in_milliseconds) Ho ...