General developer forum

Global function in AMD module?

 
Picture of Conn Warwicker
Global function in AMD module?
Core developersPlugin developers

Hi,

How can I create a global function in an AMD module, which can be called from outside the module?

E.g.

If my module was:


define(['jquery'], function($) {

    return {

        init: function(courseID) {


        // DO some stuff

 

        function my_global)function(){

                  alert('hello');

        }


        }

    }

});

 

I could call my_global_function() from within that module, but not from another script, or by putting it into any onclick events. How can I make it global, so I can call it from elsewhere?


 
Average of ratings: -
Davo
Re: Global function in AMD module?
Core developersParticularly helpful MoodlersPlugin developers

You make functions available in the same way as the 'init' function - you return it as part of the object returned by the define function, then call it by using your AMD module inside of other code.

Note you may find it easier to put your internal functions above the main return statement, then they will be available from all the functions returned, rather than just within the init function.

 
Average of ratings: -
Picture of Conn Warwicker
Re: Global function in AMD module?
Core developersPlugin developers

But how do I reference it from another script? 

If the module was:


/block/myblock/amd/src/myscript.js

define(['jquery'], function($) {

    return {

        my_function: function() {

            alert('hello');

         }

    }

});


How would I reference that function from another javascript file? I don't know what object space that's in.

 
Average of ratings: -
Picture of Justin Hunt
Re: Global function in AMD module?
Particularly helpful MoodlersPlugin developers

You would declare it is a dependency of your other script. And then it would be loaded in time and available for you to use:

/block/myblock/amd/src/otherscript.js

define(['jquery','block_myblock/myscript'], function($,myscript) {
    return {
        init: function() {
            myscript.my_function();
         }
    }
});
If you wanted to load it from a non AMD module, then life gets hard, and its going the wrong direction. 
 
Average of ratings: -
Picture of Sam Chaffee
Re: Global function in AMD module?
Core developersParticularly helpful Moodlers

To add on to what Davo said you may want to take a look at https://docs.moodle.org/dev/Javascript_Modules#Loading_modules_dynamically.

You could use that dynamic loading functionality in your event listening code.

 
Average of ratings: -