Non-IIFE Modules

Check out this discussion on Data dependency in module

I have several modules in my application that rely on data retrieved from the server. Instead of implementing them as Immediately Invoked Function Expressions (IIFEs) like traditional module patterns suggest, I am considering defining them as regular functions and initializing them within the AJAX callback function (refer to the linked answer for details). Most resources advocate for using IIFEs in the module pattern. What potential drawbacks exist, if any, in utilizing regular functions instantiated within an AJAX callback? Is this approach considered a best practice?

Answer №1

Check out this example from a previous post:

getAJAX(url, function(data){
         // write any code that want data from Ajax.
       }, true);

This piece of code includes an IIFE function call. It is referred to as an anonymous function as well. This method allows for invoking inline functions and does not follow a Modular approach.

Below is the representation of a Class in javascript:

var ClassName = function(data, pubsubService) {
var items = [];
// public function
this.generateItems = function(firstItemIndex, stopIndex) {
    var dataLength = data.length;
    stopIndex = (stopIndex < dataLength) ? stopIndex : dataLength;
    items = data.slice(firstItemIndex, stopIndex);
    pubsubService.publish('itemsGenerated');
};
// private function
var getItems = function() {
    return items;
};

return {
    generateItems : generateItems,
    getItems : getItems
};
};

In this class, generateItems is a public function and getItems is a private function.

Now, instead of creating a regular function as mentioned in your previous post, create a class as a module which contains methods of that module. Create an object and call methods like this:

Var obj = new ClassName(data,pubsubService);
obj.generateItems(firstItemIndex,stopIndex);

I believe this can aid in understanding the concept better.

Check out the following links for more information:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

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 fix the lint check error within a Vue file's styling?

Is there a way to eliminate the red wavy lines on the screen? ...

What is the method in JavaScript for a child function to trigger a Return statement in its parent function?

I have encountered a unique problem. I need to retrieve some data downloaded via ajax and return it, but neither async nor sync modes are fetching the data in time for the return. Is there a way to call the return from a child function to the parent func ...

Transmitting an array via Ajax

Is there a way to pass an array from JavaScript to PHP using Ajax? var selectedCheckboxes = $('.def-mask :checkbox:checked').serialize(); $.ajax({ url: 'ajax/battle.php', type: 'post', data: { playerReady: 1, atta ...

How can JQuery be utilized to extract the information stored in the "value" parameter of a chosen option?

I have a dropdown menu that dynamically populates its options with numbers. Here is the code for that: <select name="TheServices" id="services-selector"> <option value="" disabled selected hidden>Static Select ...

Having difficulties showing selectors content in Cheerio

Seeking assistance with extracting a table from a website, specifically trying to retrieve all the columns first. When I make the request and load the html into cheerio, I am facing an issue where the selector content does not display anything on the conso ...

How do I test Pinia by calling one method that in turn calls another method, and checking how many times it has been called

As I embark on my journey with Vue 3 and Pinia, a particular question has been lingering in my mind without a concrete answer thus far. Let's delve into the crux of the matter... Here's an example of the store I am working with: import { ref, co ...

Best practices for securing passwords using Chrome DevTools in React development

React developer tool inspector Is there a way to prevent password values from appearing in the inspector as a state when handling form submissions in ReactJS, especially when using Chrome's React developer tool? ...

Sort through information by search criteria and display outcomes with Partial view

My current challenge involves filtering data using a query and displaying the filtered results in a partial view. However, I am encountering an issue where the partial view does not update with the filtered data. How can I troubleshoot and resolve this iss ...

Using JavaScript to set the value of an input text field in HTML is not functioning as expected

I am a beginner in the programming world and I am facing a minor issue My challenge lies with a form called "fr" that has an input text box labeled "in" and a variable "n" holding the value of "my text". Below is the code snippet: <html> <head&g ...

How can I transfer the value from a textbox to a PHP variable?

Is there a way to capture values from ajax data and assign them to PHP variables? In the ajax code snippet below, I am able to pass the value through a class (edit_id). How can I store the value from the textbox in a PHP variable? Ajax $.ajax({ t ...

Troubleshooting issues with the Select List component in ReactJS

Having an issue with the select list as the onChange event is not triggering. Struggling to set the selected value from the list in the this.state variable. Any assistance on this matter would be greatly appreciated. class SelectActivity extends React.C ...

Center alignment is not possible for the Div element

Problem Every time I attempt to implement the following code (outlined below), the div only appears centered when using width: 100px;. <div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue; margin-left: auto; mar ...

Frozen Blanket: Modifying Particle Velocity

I need assistance adjusting the particle speed in this snowfall animation script. I'm having trouble locating the specific values that control the "Falling Speed." The current speed of the falling particles is too fast, and here is most of the code sn ...

JavaScript: Increasing the date by a certain number of days

I've been researching various topics and so far, I haven't come across one that addresses my specific issue. Here's the task at hand: 1) Extract a bill date in the mm/dd/yy format, which is often not today's date. 2) Add a dynamic ...

"Encountering an error in Vue3 CompositionAPI: 'quizz is not defined' while trying to call a function from the

When attempting to call a function, I am encountering an error that says "Uncaught ReferenceError: quizz is not defined." <script setup> import { defineProps } from "vue"; import { useRouter } from "vue-router"; const router = us ...

Issue with Vue.js input not updating with v-model after input sanitization in watch handler

Recently, while working with Vue 2.6, I came across an unusual issue when trying to sanitize user input. The main culprit seemed to be a custom component that housed the input field. Here's a simplified version of it: <template> <input :na ...

Navigating with Rails and Devise: How to send the user back to the original page after logging in successfully?

I have implemented the idiom described in this resource # /app/controllers/application_controller.rb class ApplicationController < ActionController::Base before_filter do |controller| redirect_to new_login_url unless controller.send(:logged_in?) ...

Ways to parse a JSON array using Javascript in order to retrieve a specific value if it is present

Below is the JSON code stored in an array: { "kind": "urlshortener#url", "id": "http://goo.gl/2FIrtF", "longUrl": "http://hike.com/?utm_source=facebook", "status": "OK", "created": "2015-09-22T13:45:53.645+00:00", "analytics": { "allTime": { ...

What is preventing me from loading Google Maps within my Angular 2 component?

Below is the TypeScript code for my component: import {Component, OnInit, Output, EventEmitter} from '@angular/core'; declare var google: any; @Component({ selector: 'app-root', templateUrl: './app.component.html', st ...

Error: The if statement is not providing a valid output

I am currently developing a basic price calculator that calculates the total area based on user input fields. While most of the program is functioning correctly, I am encountering an issue with the if statement that is supposed to determine the price rat ...