Search code examples
javascriptrequirejseventemitter

require.js shim configuration for EventEmitter2


I'm new to require.js and trying to use RosLib.js on my page by loading it with require.js. RosLib.js has a dependency to EventEmitter2.

So this is my code:

require.config({
    shim: {
        eventemitter: {
            exports: 'EventEmitter2'
        },
        roslib: {
            deps: ["eventemitter"],
            exports: "ROSLIB"
        }
    },
    paths: {
        roslib: "https://raw.github.com/RobotWebTools/roslibjs/devel/build/roslib",
        eventemitter: "https://raw.github.com/hij1nx/EventEmitter2/master/lib/eventemitter2"
    }
});

require(["roslib"], function (ROSLIB) {
    var urlname = "ws://" + location.hostname + ":9090";
    ros = new ROSLIB.Ros({
        url : urlname
    });
});

If the function Is executed somhow eventemitter2.js has an error and EventEmitter2 isn't defined:

Uncaught ReferenceError: module is not defined (eventemitter2.js:561)

Uncaught ReferenceError: EventEmitter2 is not defined (roslib.js:121)

Here is the corresponding example JsFiddle which isn't working: http://jsfiddle.net/mKyEA/1/

How do I have to configure require.js to properly initialize EventEmitter2?


Solution

  • There were two problems:

    The first problem was in the EventEmitter2 Library. I got the Uncaught ReferenceError: module is not defined (eventemitter2.js:561) exception.

    This exception should be fixed by this commit: https://github.com/Pro/EventEmitter2/commit/f829a2571b4adc66d304cb9fd5a2a5698d41c107

    The next problem is that RosLib doesn't find EventEmitter: Uncaught ReferenceError: EventEmitter2 is not defined (roslib.js:121)

    I fixed this by adding an additional require setting the global EventEmitter2. Because RosLib expects EventEmitter2 to be global but since require.js is used it isn't set on windows.EventEmitter2:

    require(["eventemitter", ], function (EventEmitter2) {
        window.EventEmitter2 = EventEmitter2;
    });
    

    Here is the new and working fiddle:

    http://jsfiddle.net/43dCV/1/