2
\$\begingroup\$

I am working on a data collection JavaScript library, and would like other members of my organization to be able to write loosely coupled plugins to extend its core functionality. I've been working on a trigger\listener (or publish\subscription) module for it and would love some feedback.

Particularly any potential unexpected pitfalls or performance gotchas I might be missing. This has the potential to be on a very heavily trafficked site and need some more eyes on it.

var eventDispatcher = (function() {
    var eventListeners = {};

    var _listener = function(eventKey, listener) {
        // Create the event's object if not yet created.
        eventListeners[eventKey] = eventListeners[eventKey] || [];

        // Add the listener to the queue
        var index = eventListeners[eventKey].push(listener) - 1;

        return {
            remove: function() {
                delete eventListeners[eventKey][index];
            }
        }
    }

    var _trigger = function(eventKey, info) {
        // If the event doesn't exist then there are no listeners in the queue, just leave.
        if(!eventListeners[eventKey]) return;

        // Cycle through event queue and fire listeners.
        eventListeners[eventKey].forEach(function(item) {
            item(typeof info !== 'undefined' ? info : {});
        });
    }

    return {
        'on'        : _listener
      , 'trigger'   : _trigger
    }
})();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.