I am working with Chris Imrie's iteration of RequireJS for ExpressionEngine making all my fieldtypes compatible. One thing I don't understand is how to call the functions that are defined in RequireJS.
https://github.com/ckimrie/RequireJS-for-EE
Here is a basic example of what I am trying to do...
var loadImage = function() {
console.log('loaded');
}
define(function () {
return loadImage;
});
How do I actually access the loadImage function? My code worked 100%, but when I started using RequireJS, the libraries behave differently. Below is a snippet from a library I am using, it's completely forked for RequireJS. If I delete the fork and use the standard jQuery call, it works without issue (even with RequireJS loading all the scripts).
Does not work:
if (typeof define === 'function' && define.amd) {
define(function () {
return loadImage;
});
} else {
$.loadImage = loadImage;
}
Does Work
$.loadImage = loadImage;
Why would jQuery libraries fork the code like this? I am concerned I am overlooking something simple, but given the context that all this code is with ExpressionEngine Fieldtypes, I don't have a problem altering the libraries.
Apologies for the answer above, I think I understand now what you are trying to do. Basically that library you are referring to (Javascript-Load-Image) has implemented AMD support (the define function you referred to) into their library and you are looking to use it in your own scripts?
RequireJS can be confusing sometimes because it is capable of loading normal scripts but also AMD JS modules. If you have a JS file that contains a JS constructor or function you are looking to make available as an module to be used by other parts of your code, its as simple as adding the define() call you mentioned above. The important part is that you need to ensure it is requested by RequireJS as an AMD module, otherwise it wont have a module name. This is as simple as omitting the ".js".
So as the example above:
//In your script that needs the loadimage library you would load it by
//specifying the path to the JS file and omitting the ".js" extension
require(["path/to/loadimage"], function(loadimage){
loadimage();
});
//If you KNOW that the library has already been loaded by RequireJS
//you can fetch it synchronously from RequireJS' memory by specifying
//its path without the .js
var loadimage = require("path/to/loadimage");
loadimage()