Montlebalm
Montlebalm

Reputation: 65

RequireJS - Load multiple instances of module

I'm trying to write a plugin in RequireJS that will create an instance of an object each time it's called.

For (contrived) example:

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 scenario, "goo" is only loaded once, so both require callbacks are passed the same object instance. This is totally understandable when you consider the problem RequireJS is trying to solve, but it's not what I need.

Is it possible to configure a plugin in such a way that it never returns a cached result? RequireJS fits my needs perfectly except for this use case. Is there any (un)official way to get the behavior I'm looking for?

Thanks.

Upvotes: 3

Views: 2230

Answers (2)

Montlebalm
Montlebalm

Reputation: 65

So I've got it figured out, but I'm definitely trying to use RequireJS plugins incorrectly.

This solution goes against the expected behavior for plugins, so you probably shouldn't do it. That being said, here's how I implemented multiple instantiations:

define("loader", {
  load: function(name, req, onload, config) {
    // Strip out the randomizer
    name = name.substring(0, name.indexOf("?"));

    // Logic you want repeated 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("loader!goo", function(instance) {
  console.log(instance.id); // 123
});

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

Upvotes: 0

Sirko
Sirko

Reputation: 74036

To illustrate my approach you would not even need a plugin, but just define a constructor function like this

define( {
  'getInstance': function(){
    var instance = new Object(); // init the object you need here
    instance.id = 42; // some more dynamic id creation here
    return instance;
  }
} );

and your actual call would then look like this:

require(["loader!goo"], function(constructor) {
  var instance = constructor.getInstance();
  console.log(instance.id);
});

Upvotes: 4

Related Questions