Search code examples
requirejssoundmanager2

SoundManager2 and require.js


SoundManager2 flash component need a specific global JavaScript variable (soundManager) to be present in global scope. This way flash player communicates with SoundManager2 JavaScript API.

The problem is that when you want to build you web application using AMD (require.js) you have to make a compromise and let this global variable to be present.

Is there any way to not break the AMD way of constructing application including SoundManager?


Solution

  • Use RequireJS shim config to wrap your non-AMD library as a module that exports the global variable: http://requirejs.org/docs/api.html#config-shim

    requirejs.config({
        paths: {
            'soundmanager2' : 'some/path/soundmanager2'
        },
        shim: {
            'soundmanager2': {
                exports: 'soundManager'
            }
        }
    });
    

    Then, require the SoundManager2 shim like any other dependency, and use it in your own module code:

    define(['soundmanager2'], function(soundManager) {
        soundManager.setup({ ... });
        soundManager.beginDelayedInit();
        // The following may help Flash see the global.
        window.soundManager = soundManager;
        return soundManager;
    });