Utilizing a modular perspective in JavaScript to load JSON files as a view

I've been working on implementing a modular view approach for retrieving data from a JSON file in my JavaScript code, but I'm facing some issues. The snippet of code where I am trying to load the JSON file is contained within a separate JS file and looks like this:

var fileConfigModule = (function () {

  var jsonData = {};

  function initialize() {
    loadJSON(function (json) {
      jsonData = json;
    });
    return jsonData;
  }

  function loadJSON(callback) {
    var request = new XMLHttpRequest();
    request.overrideMimeType("application/json");
    request.open('GET', './data.json', true);
    request.onreadystatechange = function () {
      if (request.readyState == 4 && request.status == "200") {
        callback(JSON.parse(request.responseText));
      }
    };
    request.send(null);
  }

  return {
    loadJSON: loadJSON,
    init: initialize
  }
})();

I want to utilize this module in my main file to asynchronously load the JSON data using a callback function. Here's how I plan to do it:

var jsonData = fileConfigModule.init(); 

If anyone can offer assistance on what might be going wrong here, I would greatly appreciate it. Thank you!

Answer №1

When you call an asynchronous function but expect a synchronous return value, it can lead to issues in your code.

To resolve this, consider updating your code as shown below:

var fileConfigModule = (function () {

  function initialize(callback) {
    fetchData(function (json) {
      callback(json);
    });
  }

  // The loadJSON function is actually hidden from view

  function fetchData(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', './data.json', true);
    xobj.onreadystatechange = function () {
      if (xobj.readyState == 4 && xobj.status == "200") {
        callback(JSON.parse(xobj.responseText));
      }
    };
    xobj.send();
  }

  return {
    fetchData: fetchData,
    initialize: initialize
  }
})();

You should then call the function like this:

var arData = null;
fileConfigModule.initialize(function(data){
  arData = data;
}); 

If you're unsure why the loadJSON function is being hidden, consider using it directly instead of calling the initialize function.

By calling fetchData,

var arData = null;
fileConfigModule.fetchData(function(data){
  arData = data;
}); 

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

Determining the orientation of an image in JavaScript

Currently, I am attempting to determine the orientation of images using JavaScript in order to apply a specific class to them. This process seems to be functioning correctly on Firefox, but is presenting challenges on other browsers. It appears to work bet ...

Trigger a fire event upon entering a page containing an anchor

My query is similar to this particular one, with slight differences. I am working on a page that includes an anchor, such as page.html#video1. Within this page, there are multiple sections identified by ids like #video1, #video2. Each section comprises of ...

How can I ensure the correct order when parsing JSON and performing actions with it?

After fetching JSON data from YQL and converting it into a list, my goal is to highlight specific rows in the list based on their contents. Currently, I can achieve highlighting and toggling separately using .click, but I prefer to skip that step and have ...

What is the best way to restrict users from accessing more than 5 Bootstrap Tab-Panes at once?

Users are restricted to opening only a maximum of 5 tab panes, even if there are multiple tab buttons available. If the user tries to click on the 6th tab, an alert message will be displayed. function addTab(title, url){ var tabs=$(".tabs"), tab ...

Decipher the JSON code to modify the data

I have a JSON array below. {"entries":[{"uid":155551338258538,"photo":"https:\/\/m.ak.fbcdn.net\/profile.ak\/hprofile-ak-prn1\/323887_155551338258538_1152153357_q.jpg","type":"user","text":"shikhadamodar","path":"\/shikha.dam ...

Is it possible to execute custom JavaScript code in an R Jupyter notebook?

Within my Jupyter Notebook, I am working with the R programming language and would like to integrate javascript functions into it. I'm aware that there are libraries in javascript that can be called from R, but I haven't been able to find any ex ...

Setting a Javascript value to a Controller variable within an ASP.NET MVC View

I am trying to set the javascript variable contentArea to match content.Contents in my controller. How can this be accomplished? <script language="javascript" type="text/javascript"> $("#btnTest").click(function () { var content ...

Utilizing the reduce() function to simultaneously assign values to two variables from data input

Looking to simplify the following function using reduce(), as the operations for variables selectedEnrolled and selectedNotEnrolled are quite similar. I attempted to use map(), but since I wasn't returning anything, it led to unintended side effects ...

In Flow, how is the asterisk (*) type utilized and what is its counterpart in TypeScript?

My expertise lies mostly in TypeScript, but I recently came across Flow which seems quite similar to TS in many aspects. However, one thing that caught my attention is the asterisk (*) type in Flow. Initially, I thought it was just another way of represent ...

Is there a way to adjust the label elevation for a Material UI TextField component?

I am trying to enhance the appearance of a textfield label, but I am facing some challenges with my code. textStyle: { backgroundColor: '#1c1a1a', border: 0, borderRadius: 0, width: 400, height: 66, display: 'flex&a ...

Make a JSONP request with the MIME Type set to text/plain

I've been attempting to utilize JSONP for fetching a feed from a different domain. Despite knowing that the content type should ideally be JSON or JavaScript, it is currently set as text/plain and unfortunately, I lack control over the server settings ...

You can submit a photo to a form as an attached file

I had a code that looked like this My goal is to simplify the process for users by allowing them to fill out additional information in a form without having to upload an image separately. I want to display the canvas image from the previous page in the fo ...

What is the best way to run an external JavaScript file at regular intervals?

I enjoy loading an external JavaScript file every 10 seconds, or whenever the page body is clicked (in which case, the script should only run if a few seconds have passed). If you could provide me with some documentation on this topic, that would be grea ...

Ubuntu is experiencing a DNS problem. While the URL request works perfectly on MacOSX, it is unsuccessful on Ubuntu

A custom nodeJS script has been developed to utilize the require('request').post() method. The script executes successfully on MacOSX (Travis), however encounters issues on Ubuntu (Travis). To troubleshoot, experimentation with NodeJS 'https ...

Retrieving multiple images from a directory and storing the image filenames in a JSON array

Currently, I am attempting to locate and retrieve the images stored within a specific folder using the following code. This code successfully retrieves the image names along with the total count of images. Subsequently, my goal is to save this information ...

I encounter obstacles when trying to execute various tasks through npm, such as downloading packages

Currently, I am facing an issue while trying to set up backend development using node.js on my personal computer. The problem lies with the npm command as it is not functioning correctly. Despite successfully installing a file without any errors, I am unab ...

SapUI5: Implementing a toggle functionality to display/hide one list item based on another list item's action

UI5 is a versatile framework with numerous possibilities, but sometimes I find myself struggling to implement ideas that would be easier in traditional HTML. Here's the scenario: I want to create a List with ListItems that display cities like Berlin, ...

Use Staxon to transform JSON into XML format using Java

I am currently working on converting Json to XML utilizing the following code: public static String jsonToXML1(String source) { String xmlString = null; try { StringWriter stringWriter = new StringWriter(); InputStream inputStream ...

No results returned by Mongoose/MongoDB GeoJSON query

I have a Schema (Tour) which includes a GeoJSON Point type property called location. location: { type: { type: String, enum: ['Point'], required: true }, coordinates: { type: [Number], required: true ...

Using the Volley library, you can retrieve specific data from a list view by clicking on a particular item

If I click on a particular item in the list view, how can I retrieve specific data using the Volley library? I am currently utilizing the Volley library to populate a list view with images and text. Each item in the list contains an image and accompanying ...