From faf14c41a3f8f70f3f70ccbc5607bec0aadc5867 Mon Sep 17 00:00:00 2001 From: Felix Guerin Date: Fri, 30 Oct 2020 15:48:48 -0400 Subject: [PATCH] Add window-events --- src/fx/window-events.js | 53 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/fx/window-events.js diff --git a/src/fx/window-events.js b/src/fx/window-events.js new file mode 100644 index 00000000..656d59ab --- /dev/null +++ b/src/fx/window-events.js @@ -0,0 +1,53 @@ +/** + * Centralize window events to avoid duplicates and improve global performance + * @author Deux Huit Huit + * + * App.fx.notify('window.on', { + * event: 'event', // (eg. 'scroll', 'resize', 'orientationchange', etc) + * handler: myHandlerFunction + * }); + * + * App.fx.notify('window.off', { + * event: 'sameevent', + * handler: sameHandler + * }); + * + */ +(function () { + 'use strict'; + + const listeners = {}; + + const handleEvents = (event) => { + const handlers = listeners[event.type]; + handlers.forEach((handler) => { + handler(event); + }); + }; + + const on = (key, { event, handler }) => { + const evt = listeners[event]; + if (evt) { + evt.add(handler); + return; + } + listeners[event] = new Set(); + listeners[event].add(handler); + window.addEventListener(event, handleEvents); + }; + + const off = (key, { event, handler }) => { + const evt = listeners[event]; + if (!evt) { + return; + } + evt.delete(handler); + if (evt.size === 0) { + window.removeEventListener(event, handleEvents); + delete listeners[event]; + } + }; + + App.fx.exports('window.on', on); + App.fx.exports('window.off', off); +})();