Skip to content

Instantly share code, notes, and snippets.

@yairEO
Last active August 11, 2023 07:08
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yairEO/cb60592476a4204b27e83048949dbb45 to your computer and use it in GitHub Desktop.
Save yairEO/cb60592476a4204b27e83048949dbb45 to your computer and use it in GitHub Desktop.
Event Handler Namespace in Vanilla JavaScript
var events = (function(){
function addRemove(op, events, cb){
if( cb )
events.split(' ').forEach(name => {
var ev = name.split('.')[0]
cb = cb || this._eventsNS[name]
this[op + 'EventListener'].call(this, ev, cb)
if(op == 'add')
this._eventsNS[name] = cb
else
delete this._eventsNS[name]
})
}
function on(events, cb){
this._eventsNS = this._eventsNS || {} // save the _eventsNS on the DOM element itself
addRemove.call(this, 'add', events, cb)
return this
}
function off(events, cb){
addRemove.call(this, 'remove', events, cb)
return this
}
// need to work on this method, it is the hardest.
// currently I do not know how to dispatch real events (with namespace) like UIEvent, KeyboardEvent, PointerEvent and so no
function trigger(eventName, data){
var e;
// Don't do events on text and comment nodes
if( elem.nodeType === 3 || elem.nodeType === 8 || !eventName ) return
try {
e = new CustomEvent(eventName)
}
catch(err){ console.warn(err) }
this.dispatchEvent(e)
}
return { on, off, trigger }
})()
// Extend the DOM with these above custom methods
window.on = document.on = Element.prototype.on = events.on;
window.off = document.off = Element.prototype.off = events.off;
window.trigger = document.trigger = Element.prototype.trigger = events.trigger;
@yairEO
Copy link
Author

yairEO commented Oct 31, 2017

Use Example:

window
  .on('mousedown.foo', ()=> console.log("namespaced event listener will be removed after 3s"))
  .on('mousedown.bar   mousedown.abc', ()=> console.log("event listener will NOT be removed"))
  .on('mousedown.baz', ()=> console.log("event listener will fire once"), {once: true});

// after 3 seconds remove the event with `foo` namespace
setTimeout(function(){
    window.off('mousedown.foo')
}, 3000)

@shaan1974
Copy link

shaan1974 commented Dec 21, 2019

// TRIGGER
trigger: function(event)
    {
        //  VARS
        var eventName = (event.split('.').length === 1) ? event : event.split('.')[0];
        var hasNamespace = (event.split('.').length === 1) ? false : true;
        var ns = this.namespaces;
        var key;
        this.tmp_namespaces = {};

        //  LOOP TO GET RELATED EVENT TO THE TRIGGER INTO NAMESPACES
        for (key in ns)
        {
            if (ns.hasOwnProperty(key))
            {
                if (hasNamespace === true && key === event)
                {
                    cb = ns[key];
                    this.addEventListener("fake", cb, false);
                    this.tmp_namespaces[event] = cb;
                }
                else if (hasNamespace === false && key.indexOf(eventName) === 0)
                {
                    cb = ns[key];
                    this.addEventListener("fake", cb, false);
                    this.tmp_namespaces[event] = cb;
                }
            }
        }

        //  DISPATCH FAKE EVENT(S)
        var e = new Event("fake");
        e.target = this;
        e.currentTarget = this;
        this.dispatchEvent(e);

        //  REMOVE FAKE EVENT(S)
        for (key in this.tmp_namespaces)
        {
            this.removeEventListener("fake", this.tmp_namespaces[key]);
        }
        delete this.tmp_namespaces[event];

        return this;
    }

//  Extend the DOM
window.trigger = Element.prototype.trigger = events.trigger;

@yairEO
Copy link
Author

yairEO commented Dec 22, 2019

@shaan1974 - dispatching new Event is not good since you need to dispatch a different event according to the type of the event, for example there are UIEvent, KeyboardEvent, MouseEvent and many others. Each has unique set of properties that act as the callback listener argument, and they should be kept it is likely a developer is expecting at least some of the properties of the event, like x, y of a pointer click for example.

@shaan1974
Copy link

I use this technique because if you don't do that it's not possible to trigger an event with a specific namespace. In my case i use it to fake "Input" event, it's why i set the target and the currentTarget.

@JangCool
Copy link

JangCool commented Aug 3, 2021

Thank you. I'll use this source code well.

@sKopheK
Copy link

sKopheK commented Feb 19, 2022

  1. you know off() as presented in the usecase cannot work as you are not passing any cb thus addRemove() method won't do anything?
  2. calling off() before on() breaks the internet :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment