Reputation: 538
We're building web app that uses RequireJS for modular development/dependency management.
We kick things of with the following:
<script data-main="js/main" src="js/libs/require/require.js"></script>
The web app also uses a third-party applet that is required for communication with a mainframe system. The applet has a callback function that executes once the api for communicating with it has been initialized, with the api object passed in as a parameter. e.g.
/*
* This function is invoked automatically after the Reflection session has
* completed its initialization. A reference to the JavaScript API is passed
* in as a parameter.
*/
function jsapiInitialized( api ) {
return api;
}
Basically, the above needs to be a dependency for many of the modules within the app.
How can I make the above function a module dependency, so the api object is available to those modules requiring it?
Upvotes: 1
Views: 1010
Reputation: 4145
It seems that you want to use asynchronous like define
method for your API. To do it with require.js you'll need to create a small plugin. As result you'll have the following files:
1) myapi.js (API simulation file)
// this is actually simulation of your third party code
setTimeout(function() {
if(typeof jsapiInitialized === 'function') jsapiInitialized('hello!');
}, 1000);
2) myplugin.js (plugin which handles your API callback)
define(function(){
return {
load : function(name, req, onLoad, config){
window.jsapiInitialized = function(api) {
onLoad(api);
};
require([name]);
}
};
});
3) main.js (to test your plugin)
require(['myplugin!myapi'], function(api){
alert(api);
});
(where "myapi" can be a path to your real API script)
Upvotes: 3