function not defined errors in AMD JS code

i am integrating a web service into my website from a t-shirt vendor and they provide a PHP template for a shop, which i have used.

the version of the code for my 1.8.x site was mostly working, but when i upgraded the code for 1.11.x and converted the JS file into AMD JS, i started seeing console errors in the browser that state that some of the functions are not defined when i call them. i have looked at every aspect that i can see that could be the cause of the problem but so far i haven't found the real cause. i'm wondering if anyone can point me to the solution..

the code is basically of this form:

 

define(function(require)
{
    var $ = require('jquery');  
    var elgg = require('elgg');

    function changeImage(imageID, imageSource, viewID)
    {
        $('#' + imageID).attr('src', imageSource);
        if (viewID != '')
        {
           $('#' + imageID).data('lastValue',viewID);
        }
    }; 
});

originally, this (and other functions) were inside a dom.ready function, but i have now tested the code with and without that dom.ready check and in both cases the function changeImage is identified as being undefined when it is called from within an inline onclick event handler that is part of a link within the rendered page. is this an AMD problem or am i missing something simple about scoping?

thanks

  • This is a simple matter of scoping: Functions and variables defined in an AMD module are not available globally. Actually this is true in JS for any function or variable defined inside a function. They are not available globally. This is a Good Thing, since dumping random stuff into the global namespace can cause conflicts with other libraries that are doing the same, resulting in hard-to-find bugs.

    Instead of having an inline onclick handler, run jQuery's event delegation one time (e.g. run it inside an AMD module):

    $(document).on('click', '.class-name', function handler() { ... });

  • aha, ok thanks - i do re-member reading about that now.. i was just 'hoping' there might be another explanation. i didn't write the code that uses the inline javascript - so this just means i need to go through and update a whole library before i can use it. so.. i'll do that now then!