RequireJS - 加载多个模块实例

时间:2013-08-19 15:29:48

标签: javascript requirejs

我正在尝试在 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 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分: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
});