Vanilla namespace of JavaScript events, e.g. in jQuery

In jQuery, when you set an event, you can skip it. This means that (if you want) you can have several events of the resize window, for example, and be able to unleash them separately, without canceling all the events on this selector.

Example jQuery namespace:

$(window).on('scroll.myScrollNamespace, function() ...

I am wondering how I can create a namespace in simple JavaScript. This clearly didn't work:

window.addEventListener('resize.myScrollNamespace', function() ...

+7
javascript jquery javascript-events events
source share
2 answers

If instead of an anonymous function:

 window.addEventListener('resize', function () {...}); 

you are using a named function:

 window.addEventListener('resize', function myScroll() {...}); 

then you can use:

 window.removeEventListener('resize', myScroll); 

Make sure you have myScroll in the area. When you delete listeners in a different place than you add them, perhaps you should define your functions in some external area and use their names in addEventListener in the same way as in removeEventListener :

 function myScroll() { // ... } window.addEventListener('resize', myScroll); window.removeEventListener('resize', myScroll); 

If you want to delete several listeners at once, you will need to save them in some kind of array and call removeEventListener for each of its elements.

See the documentation for EventTarget.removeEventListener() .

+7
source share

As @rsp's answer correctly solves the problem of decoupling the right handler, in fact it does not answer the namespace problem. To handle this, you need to do a little more code as follows:

 function on(elm, evtName, handler) { evtName.split('.').reduce(function(evtPart, evt) { evt = evt ? evt +'.'+ evtPart : evtPart; elm.addEventListener(evt, handler, true); return evt; }, ''); } function off(elm, evtName, handler) { evtName.split('.').reduce(function(evtPart, evt) { evt = evt ? evt +'.'+ evtPart : evtPart; elm.removeEventListener(evt, handler, true); return evt; }, ''); } // Your handler function onScroll(e) { ... } // To bind it on(window, 'scroll.myScrollNamespace', onScroll); // To unbind it off(window, 'scroll.myScrollNamespace', onScroll); 

So, to summarize: this actually sets up several event listeners - one for each part of your namespace. Unfortunately, this functionality, unfortunately, is not supported, but, as you see, it can be achieved relatively easily. Just be careful that although this script supports a deep namespace (e.g. scroll.parent.child ), it will bind a lot of event listeners (in this case 3) and therefore not practical.

You could make it more perfect, but it's all done.

0
source share

All Articles