Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6662255
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T02:22:13+00:00 2026-05-26T02:22:13+00:00

How much can I stretch RequireJS to provide dependency injection for my app? As

  • 0

How much can I stretch RequireJS to provide dependency injection for my app? As an example, let’s say I have a model that I want to be a singleton. Not a singleton in a self-enforcing getInstance()-type singleton, but a context-enforced singleton (one instance per “context”). I’d like to do something like…

require(['mymodel'], function(mymodel) {
   ...
}

And have mymodel be an instance of the MyModel class. If I were to do this in multiple modules, I would want mymodel to be the same, shared instance.

I have successfully made this work by making the mymodel module like this:

define(function() {
    var MyModel = function() {
        this.value = 10;
    }
    return new MyModel();
});

Is this type of usage expected and common or am I abusing RequireJS? Is there a more appropriate way I can perform dependency injection with RequireJS? Thanks for your help. Still trying to grasp this.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T02:22:14+00:00Added an answer on May 26, 2026 at 2:22 am

    This is not actually dependency injection, but instead service location: your other modules request a “class” by a string “key,” and get back an instance of it that the “service locator” (in this case RequireJS) has been wired to provide for them.

    Dependency injection would involve returning the MyModel constructor, i.e. return MyModel, then in a central composition root injecting an instance of MyModel into other instances. I’ve put together a sample of how this works here: https://gist.github.com/1274607 (also quoted below)

    This way the composition root determines whether to hand out a single instance of MyModel (i.e. make it singleton scoped) or new ones for each class that requires it (instance scoped), or something in between. That logic belongs neither in the definition of MyModel, nor in the classes that ask for an instance of it.

    (Side note: although I haven’t used it, wire.js is a full-fledged dependency injection container for JavaScript that looks pretty cool.)


    You are not necessarily abusing RequireJS by using it as you do, although what you are doing seems a bit roundabout, i.e. declaring a class than returning a new instance of it. Why not just do the following?

    define(function () {
        var value = 10;
    
        return {
            doStuff: function () {
                alert(value);
            }
        };
    });
    

    The analogy you might be missing is that modules are equivalent to “namespaces” in most other languages, albeit namespaces you can attach functions and values to. (So more like Python than Java or C#.) They are not equivalent to classes, although as you have shown you can make a module’s exports equal to those of a given class instance.

    So you can create singletons by attaching functions and values directly to the module, but this is kind of like creating a singleton by using a static class: it is highly inflexible and generally not best practice. However, most people do treat their modules as “static classes,” because properly architecting a system for dependency injection requires a lot of thought from the outset that is not really the norm in JavaScript.


    Here’s https://gist.github.com/1274607 inline:

    // EntryPoint.js
    define(function () {
        return function EntryPoint(model1, model2) {
            // stuff
        };
    });
    
    // Model1.js
    define(function () {
        return function Model1() {
            // stuff
        };
    });
    
    // Model2.js
    define(function () {
        return function Model2(helper) {
            // stuff
        };
    });
    
    // Helper.js
    define(function () {
        return function Helper() {
            // stuff
        };
    });
    
    // composition root, probably your main module
    define(function (require) {
        var EntryPoint = require("./EntryPoint");
        var Model1 = require("./Model1");
        var Model2 = require("./Model2");
        var Helper = require("./Helper");
    
        var entryPoint = new EntryPoint(new Model1(), new Model2(new Helper()));
        entryPoint.start();
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've simplified this example as much as I can. I have a remote function:
I know my question reads a bit like that 'how much wood can a
If I have this in a migration: t.text :body How much text can I
I have a Grid with these rows settings: (I can't post much code, sorry)
I have a frustrating problem that I would much appreciate some help with. I
How much traffic can one web server handle? What's the best way to see
How much slower can I reasonably expect perform: to be than a literal message
Is there any limit on how much data can be stored using GM_setValue ?
I need to keep as much as I can of large file in the
I'm trying to reduce as much as I can my VB.Net assembly side, and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.