Global function in AMD module?

Global function in AMD module?

by Conn Warwicker -
Number of replies: 4
Picture of Core developers Picture of Plugin 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: -
In reply to Conn Warwicker

Re: Global function in AMD module?

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin 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.

In reply to Davo Smith

Re: Global function in AMD module?

by Conn Warwicker -
Picture of Core developers Picture of Plugin 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.

In reply to Conn Warwicker

Re: Global function in AMD module?

by Justin Hunt -
Picture of Particularly helpful Moodlers Picture of Plugin 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.