RequireJS - 加载多个模块实例

3
我正在尝试使用RequireJS编写一个插件,每次调用时都会创建一个对象实例。
例如(虚构):
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!
});

在这种情况下,“goo”只被加载一次,因此两个需要回调函数的对象实例都被传递了相同的实例。当您考虑RequireJS尝试解决的问题时,这是完全可以理解的,但这不是我需要的。

是否有可能以这样的方式配置插件,使其永远不返回缓存结果? RequireJS完全符合我的需求,除了这种用例。是否有任何(非)官方方法可以获得我正在寻找的行为?

谢谢。


2
为什么不在你的模块中导出一个构造函数并调用它呢? - Sirko
@Sirko,您能否提供一个简单的例子吗?我不确定我理解了。 - Montlebalm
2个回答

4
为了说明我的方法,您甚至不需要插件,只需要定义一个构造函数,如下所示。
define( {
  'getInstance': function(){
    var instance = new Object(); // init the object you need here
    instance.id = 42; // some more dynamic id creation here
    return instance;
  }
} );

你的实际调用将会像这样:

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

谢谢,但我试图避免将“goo”定义为RequireJS模块。在这种情况下,“loader”实际上是一个工厂,用于实例化“goo”或类似的内容。听起来我正在尝试使用插件架构进行非预期的目的。 - Montlebalm

0

我已经理解了,但是我肯定在错误地使用RequireJS插件。

这种解决方案违反了插件的预期行为,所以你可能不应该这样做。尽管如此,以下是我如何实现多个实例的方法:

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
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接