Search code examples
javascriptrequirejsjs-amd

how can access require.js module's function?


i want to use a.js module's test();

my method: - a.js -

define(function (require, exports, module) {
    function test(val) {
        alert(val);
    }
    window.test = test;
}

have other methods ? sorry my english very pool, I hope you can understand, thx!


Solution

  • You shouldn't usually assign to globals from a RequireJS module (i.e. set properties on window).

    /path/test.js

    define(function() {
        function test(val) {
            alert(val);
        }
        return test;
    }
    

    /path/app.html

    <!-- import requirejs ... -->
    
    <script>
    // Use the return value from the "test" module.
    require(["test"], function(testFn) {
        testFn("hello");
    });
    </script>