Calling methods in RequireJs modules from HTML elements such as onclick handlers

One benefit from using AMD is to drop the need for namespaces. Trying to create them again with RequireJS will go against the patterns AMD promotes.

With regard to using main.js, this is only really appropriate when you have a single page app and all your code be reference from one place. You’re free to make additional calls to require and load other modules as you need them.

Using your example from above, you could approach it this way:

foo.js

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

    // Some set up 
    // code here

    // Return module with methods
    return {
        bar: function() {

        }
    }


});

page.js

require(['foo'], function(foo) {

    // jQuery loaded by foo module so free to use it
    $('.button').on('click', function(e) {
        foo.bar();
        e.preventDefault();
    });

});

Then in your page request the page.js file with require.

Using your example above:

require({
    // config stuff here
}, [ 'page' ]);

Or loading it in the page further down:

<script>
    require(['page']);
</script>

Some additional points

  • Using the pattern above, page.js could easily require many other
    modules to load other page related functionality.

  • Where before you would attach members to your global namespace, you
    now split that code into separate modules that can be re-used on
    any page. All without reliance on a global object.

  • Using require this way to attach events to your DOM elements will
    most likely rely on the DOM Ready module provided by RequireJS

Leave a Comment