Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make my javascript function requirejs/amd friendly? [duplicate]

I have created a javascript library which adds only one global object to the global space.

The global object happens to be a function and the name of the function matches the name of the file.

This is how it looks:

filename: myfunction.js

code:

myfunction = function() {
   ...
};

How do I make my library compliant with amd and require.js ?

like image 965
Zo72 Avatar asked Dec 20 '22 03:12

Zo72


1 Answers

The Requirejs Docs tell you all about how to make an AMD compliant module. However, information on how to keep a module working when used without AMD (<script> tag) is hard to find there. Anyway, when in a Requrirejs context, the "define" method is defined. Otherwise, the example below just uses window.x (not the most elegant solution) to expose the function to the global space from within a closure.

(function (module) {
    if (typeof define === "function" && define.amd) {
        define(function () { return module; });
    } else {
        window.myfunction = module.myfunction;
    }
}({
    myfunction: function () {
        /* ... */
    }
}));

See also: https://stackoverflow.com/a/14033636

like image 92
depoulo Avatar answered Feb 24 '23 07:02

depoulo