简体   繁体   English

将requireJS模块公开给全局名称空间的正确方法是什么?

[英]What's the correct way to expose a requireJS module to the global namespace?

I want to expose a Javascript API as a standalone library without polluting their global namespace. 我想将Javascript API作为独立的库公开,而不污染其全局名称空间。 I've created the wrapper so I don't pollute their own requireJS according to http://requirejs.org/docs/faq-advanced.html . 我已经创建了包装器,因此不会根据http://requirejs.org/docs/faq-advanced.html污染自己的requireJS。 I've simplified what I have so far as below, but I'm not sure if this is the correct way or if I should be doing it some other way. 我已经简化了到目前为止的内容,但是我不确定这是正确的方法还是应该采用其他方法。

var MyApi = MyApi || {};
var MyApiRequireJS = (function() {
  // require.js pasted here
  return {requirejs: requirejs, require: require, define: define};
})();

(function(require, define, requirejs) {
  require.config({
    baseUrl: 'js/scripts',
    waitSeconds: 30,
  });  

  define( 'myapi', ['jquery', 'underscore'],
    function($, _) {
      $.noConflict(true);
      _.noConflict();
      function api(method, args, callback) {
        // do stuff here
      }
      return {api: api};
    }
  );

  require( ['myapi'], function( myapi ) {
    MyApi = myapi;
  });
}(MyApiRequireJS.require, MyApiRequireJS.define, MyApiRequireJS.requirejs));

Sites using this library would include a script tag referencing the above code and then call the api using 使用此库的网站将包含引用上述代码的脚本标签,然后使用

MyApi.api('some_remote_method', {foo: 'bar'}, function(result) {
  // handle the result
});

I think you're trying to anticipate someone else's problem by making it your problem, but I don't think you can really reasonably do that. 我认为您正在尝试通过使其他人成为您的问题来预料到其他人的问题,但是我认为您不能真正合理地做到这一点。 The page that you link to is designed to let people who already have Javascript globals named "require" or "define" rename the RequireJS globals to something different. 您链接到的页面旨在让已经拥有Java全局变量名为“ require”或“ define”的用户将RequireJS全局变量重命名为其他名称。 It's not intended to create two separate RequireJS instances that independently resolve dependencies. 并不是要创建两个单独的RequireJS实例来独立解决依赖关系。

That said, if you are really trying to minimize the namespace pollution, then you should expose exactly one name -- MyApi. 就是说,如果您实际上是想最大程度地减少名称空间污染,则应该只公开一个名称-MyApi。 Write one monster closure that includes your private copy of RequireJS as well as your API code, and have it return only the methods you want to expose on your API. 编写一个怪物闭包,其中包括您的RequireJS私有副本以及您的API代码,并使它仅返回您要在API上公开的方法。

It's probably much friendlier/simpler to deliver your API in two versions, one that defines a requireJS module, and one that has no requireJS dependency. 提供两个版本的API可能更友好/更简单,一个版本定义了requireJS模块,而另一个版本则没有requireJS依赖性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM