What is the right way to open the requireJS module for the global namespace?

I want to open the Javascript API as a separate library without polluting their global namespace. I created a shell, so I do not pollute their requireJS according to http://requirejs.org/docs/faq-advanced.html . I have simplified what I still have, but I'm not sure if this is right, or if I have to do it differently.

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 will include a script tag that links to the above code, and then call api using

 MyApi.api('some_remote_method', {foo: 'bar'}, function(result) { // handle the result }); 
+8
javascript requirejs
source share
1 answer

I think you are trying to foresee someone else's problem by making it your problem, but I do not think that you really can do it. The page you are linking to is designed to let people who already have Javascript globals named "require" or "define" rename globals RequireJS to something else. It is not intended to create two separate instances of RequireJS that independently resolve dependencies.

However, if you are really trying to minimize namespace pollution, then you should only specify one name - MyApi. Write one monster closure that includes your personal copy of RequireJS, as well as your API code, and return only the methods that you want to open in your API.

Most likely, it is much simpler / easier to provide your API in two versions, which defines the requireJS module, and one that does not require a JS dependency.

0
source share

All Articles