RequireJS - Enabling the loading of multiple module instances

I am working on a custom RequireJS plugin that needs to create a new object instance every time it is called.

For illustration purposes, consider the following:

define("loader", {
  load: function(name, req, onload, config) {
    var instance = GlobalGetter.get(name);
    instance.id = new Date().getTime() * Math.random();
    onload(instance);
  }
});

require(["loader!goo"], function(instance) {
  console.log(instance.id); // 12345
});

require(["loader!goo"], function(instance) {
  console.log(instance.id); // 12345 SAME!
});

In this example, the "goo" module is only loaded once, causing both require callbacks to receive the same object instance. While this behavior makes sense in the context of RequireJS, it does not align with my requirements.

Is there a way to configure a plugin so that it always returns a fresh result? Although RequireJS generally meets my needs, I'm looking for a solution to address this specific scenario. Are there any official or unofficial methods to achieve the desired outcome?

Thank you.

Answer №1

If you want to see my method in action, you don't even have to use a plugin. Simply define a constructor function like the one below:

const customConstructor = {
  'createInstance': function(){
    let obj = new Object(); // initialize the necessary object here
    obj.id = 42; // add some dynamic id creation logic here
    return obj;
  }
};

Then, when you make the actual call, it will look something like this:

require(["loader!bar"], function(constructor) {
  const newInstance = constructor.createInstance();
  console.log(newInstance.id);
});

Answer №2

After some experimentation, I've managed to find a workaround that involves using RequireJS plugins in a non-standard way.

While this approach deviates from the typical usage of plugins and is not recommended, I was able to achieve multiple instantiations with the following implementation:

define("customLoader", {
  load: function(name, req, onload, config) {
    // Removing any query parameters
    name = name.substring(0, name.indexOf("?"));

    // Repeating desired logic each time
    var fn = Something.GetClass(name);
    var instance = new fn();
    instance.id = Math.random();
    onload(instance);
  },
  normalize: function(name, normalize) {
    return name + "?" + Math.random();
  }
});

require("customLoader!goo", function(instance) {
  console.log(instance.id); // 123
});

require("customLoader!goo", function(instance) {
  console.log(instance.id); // 456
});

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

Implementing Winston logging into a React JS project

I am looking to integrate Winston logging into my React application that was created using create-react-app. First, I installed Winston by running the following command: npm install winston Next, I imported Winston into my app.js file like so: import win ...

Exploring the differences between utilizing Node JS Express for server-side development and displaying console output to

Recently, I started delving into the world of node js and came across IBM's speech to text sample application (https://github.com/watson-developer-cloud/speech-to-text-nodejs). This app utilizes the express framework and showcases transcribed audio fr ...

Displaying a loading progress bar while the website is being loaded using Javascript

Currently working on developing a GUI site, I am looking to implement a progress bar. However, I require some JavaScript code that can detect the loading status of the site along with the number of elements/images that have been loaded so far, as well as d ...

The imported `theme` as `theme` was not visible in the file './theme'. The only possible export in the file is `default`

Encountering an error while attempting to export the theme from the index.js file. Below is the snippet of code present in the index.js file. import { createTheme } from "@mui/material"; import shadows from "./shadows"; import typograph ...

Discovering a particular element involves iterating through the results returned by the findElements method in JavaScript

I am attempting to locate and interact with a specific item by comparing text from a list of items. The element distinguished by .list_of_items is a ul that consists of a list of li>a elements. I am uncertain about how to transfer the determined elemen ...

Error: No route found at this location

I've been following a tutorial on integrating Evernote with IBM's DOORS Next Generation and I added the code highlighted below. // app.js app.get("/notebooks", function(req, res) { var client = new Evernote.Client({ token: req.session.oauth ...

Dropdown element vanishes upon selecting in HTML

Utilizing Angular's ng-init to populate a rest call function and populate $scope.races before filling up the dropdown. Initially, everything appears to be working correctly. However, upon selecting an option from the dropdown menu, it immediately cle ...

Mastering VSCode IntelliSense: Unleashing the Power of Type Declarations

In my JavaScript projects, I aim to include TypeScript types sparingly to leverage IntelliSense for better code completions and receive warnings about type-related issues. To set up typechecking in JS, I created a jsconfig.json file and rely mostly on JSD ...

Utilizing modal dialogs in HTML and navigating back to the previous page

I'm currently learning about HTML, CSS, JavaScript, and SQL. Here is some context: Imagine a scenario where I am developing a website to manage information on dogs, their owners, and the relationships between them. All this data is stored in an SQL ...

Error Message: SCRIPT5 - Permission Denied When Trying to Open PDF with Javascript

Despite searching through multiple posts on SO, I have yet to find a solution to my issue. We operate a web form within our LAN that utilizes Javascript's OPEN function to open PDF files. Up until recently, everything was working smoothly. However, ...

Removing a selected row from a data table using an HTTP request in Angular 2

I am working with a table that has data retrieved from the server. I need to delete a row by selecting the checkboxes and then clicking the delete button to remove it. Here is the code snippet: ...

The onChange event does not function properly on formatted Mui sliders

Having an issue with the Mui styled Slider. The value is not changing smoothly and it seems like the thumb of the slider is not draggable. You can see the issue reproduced here. Thank you in advance. ...

What is the purpose of using Array.prototype.slice.call(nodeList) for handling DOM elements?

Many JavaScript libraries like jQuery and Zepto frequently use Array.prototype.slice.call on querySelectorAll(), getElementsByTag, or ClassName results. Despite browsing numerous questions and answers on StackOverflow about this topic, I understand that it ...

Ways to achieve 8 columns in a single row using Javascript and Bootstrap

Recently, I created a simple function for searching movies and manipulating them in the DOM. The issue arises when a movie name is entered and the API response returns around 20-30 recommendations. I wanted to display this fetched data in 8 columns per row ...

Do all descendants consistently trigger rerenders?

Recently, I was exploring the React new documentation here, where I came across this interesting piece of information: The context value mentioned here is a JavaScript object with two properties, one being a function. Whenever MyApp re-renders (for examp ...

Angular Selectable Drop-down Menu

I'm facing an issue with using angularjs for dropdown with multiple selection. When I try to include 2 dropdowns in the same form, only one of them gets initialized properly. Here is a sample code snippet http://jsfiddle.net/vUSPu/1221/. Can someone p ...

I am facing an issue with the DOM object in my ejs template when used under the script tag. How can I resolve this problem?

<%-include ("partials/header.ejs") %> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <header> <!--NAVIGATION BAR--> <img class="calender-pic" src="images/calendar.png ...

Utilize Javascript to conceal images

On a regular basis, I utilize these flashcards. Recently, I have started using images as answers. However, I am facing an issue - I am unable to conceal the pictures. My preference is for the images to be hidden when the webpage loads. function myShowTe ...

Managing browser navigation within a web application

I am currently developing a web-based application for internal use in the company I work for. The application is quite intricate, featuring numerous forms that will enable users to both view and input data, which will then be stored in a database upon savi ...

Deploying a static website using Node.JS without relying on any frameworks

I am currently working on deploying static web pages, which include HTML, CSS, and JS files, onto Node.js without utilizing any frameworks such as Express. I started by placing all the necessary webpage files into a public folder and then called the index. ...