Skip to content
This repository has been archived by the owner on Feb 12, 2021. It is now read-only.

Add window-events #501

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions src/fx/window-events.js
Original file line number Diff line number Diff line change
@@ -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);
})();