requirejs插件在新的上下文中加载模块

时间:2011-06-10 04:34:07

标签: javascript requirejs

我希望在页面上多次加载模块,并为每个实例提供唯一的上下文。有两种常规方法可以做到这一点。

  1. 模块可以返回构造函数
  2. 我可以显式运行require方法,提供上下文ID。
  3. 其中任何一种都适用于我的情况,但我想要第三种选择。 :)

    我想要一个requirejs插件,它会在新的上下文中向我返回一个模块。即,

    require(["new!some/module"], function(SomeModule) {
        // SomeModule, here, is in its own context.  If i were to run this
        // method call again, SomeModule would be in a new context.
    });
    

    我开始考虑构建一个插件来执行此操作...

    load: function (name, req, load, config) {
        var index = get_unique_index();
        req({context:index}, [name], function(value) {
            if(!config.isBuild){
                load(value);
            }
        });
    }
    

    但{context:index} dict在这里不起作用......想法?

1 个答案:

答案 0 :(得分:1)

使用全局require函数,而不是使用传递给load的本地req,只需调用require()。传递给load的本地文件已绑定到上下文。

相关问题