Hemanth's Scribes

javascript

JavaScript Event tracking and management

Author Photo

Hemanth HM

Thumbnail

Events play a major role in almost all JavaScript libraries. Experimenting on the same lines, I coded a simple prototype with raw JavaScript to make basic event management and tracking easier and named it event.js.

So what does event.js do?

  • Add events to DOM elements [Cross-Browser support]
  • Get the event type for the particular DOM element
  • Remove a single or all events

Here is the code for event.js:

/**
 * @author  : Hemanth.HM
 * @license : GPLv3
 */

var TrackEvents = (function() {
    'use strict';

    function TrackEvents() {
        this._listeners = [];
    }

    /**
     * @typedef {{node: !Node,
     *            type: string,
     *            listener: Function,
     *            useCapture: boolean}}
     */

    TrackEvents.prototype = {
        /**
         * Add an event listener.
         * @param {!Node} node DOM element, that needs an event handler to be attached.
         * @param {string} type The type of event.
         * @param {Function} listener The listener to add.
         * @param {boolean} useCapture invoke during the capture phase?
         */
        add: function(node, type, listener, useCapture) {
            if (!node || !type || !listener) return null;
            if (!useCapture) useCapture = false;

            var h = {
                node: node,
                type: type,
                listener: listener,
                useCapture: useCapture
            };

            this._listeners.push(h);

            /* It all boiled down to a single line: Cross Browser event handling */
            node.addEventListener ? 
                node.addEventListener(type, listener, useCapture) : 
                node.attachEvent ? 
                    node.attachEvent('on' + type, listener, useCapture) : 
                    node['on' + type] = listener;
        },

        /**
         * Remove any specified event listeners added with this TrackEvents.
         * @param {!Node} node The DOM node to remove a listener from.
         * @param {?string} type The type of event to remove.
         */
        remove: function(node, type) {
            this._listeners = this._listeners.filter(function(h) {
                if (h.node == node && (!type || (h.type == type))) {
                    TrackEvents.removeEventListener_(h);
                    return false;
                }
                return true;
            });
        },

        /**
         * Get the event type bound to that DOM element
         * @param {!Node} node DOM element
         */
        get: function(node) {
            var k;
            this._listeners.filter(function(h) {
                if (h.node == node)
                    k = h.type;
            });
            return k;
        },

        /* Remove all event listeners added with this TrackEvents. */
        removeAll: function() {
            this._listeners.forEach(TrackEvents.removeEventListener_);
            this._listeners = [];
        }
    };

    /**
     * Remove a single event listener given its tracker entry.
     * @param {TrackEvents.Entry} h The entry describing the listener to remove.
     * @private
     */
    TrackEvents.removeEventListener_ = function(h) {
        h.node.removeEventListener ?
            h.node.removeEventListener(h.type, h.listener, h.useCapture) :
            h.node.detachEvent(h.type, h.listener);
        h.node['on' + h.type] = null;
    }

    return TrackEvents;
})();

How to use event.js?

  • Include event.js in your head (I meant the head tag)
  • Instantiate: event = new TrackEvents();
  • Use the event object to add, remove, remove all or to get the event for a specific DOM element

P.S: There are always better ways of doing things, do let me know your way!

#javascript
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.