【发布时间】:2013-06-26 20:26:48
【问题描述】:
我正在使用 RequireJs 在我公司的主要网站上加载 AMD 模块。我们还使用 requireJS 来加载托管在不同域上的模块。 requireJS 使用“上下文”字段支持这一点; IE。使用单独的 baseUrl 创建单独的沙盒环境。
当前的问题是当我们希望两个独立的上下文共享一个公共对象时;例如。 jquery(以避免加载它两次)或在小部件之间触发事件的 pubsub 实现。
我想出了一种在上下文之间注入模块的方法,使用定义函数和全局 requireJS
main.js - 托管在 http://example.com/src/main.js
require(['jquery'], functin($){
// create sandbox/contexted instance of requireJs
var sandbox = requireJS.config({
context: "myContext",
baseUrl : 'http://otherdomain.com/src'
});
// load module (with internal dependencies) from other domain
sandbox.require(['modules/bootstrap.js'], function(bootstrap){
bootstrap.run();
});
});
bootstrap.js - 例如。托管在http://widgets.com/src/modules/bootstrap.js
define(function(){
// define jquery into sandboxed environemnt
requireJs('jquery', function($) {
define('jquery', function(){
return window.jQuery;
});
});
// obtain sandboxed instance from parent
var sandbox = requireJs.config({
context: "myContext"
});
sandbox(['jquery'], function($){
console.log($);
});
});
问题是,如果我定义 jquery(或任何其他返回函数的模块),tje "requreJS"-way(不使用全局变量)它总是会抛出错误
// define jquery into sandboxed environemnt
requireJs('jquery', function($) {
define('jquery', $);
});
这是错误还是功能?
【问题讨论】: