Skip to content

Commit

Permalink
Refactor on and once functions
Browse files Browse the repository at this point in the history
  • Loading branch information
demiazz committed May 3, 2017
1 parent ce94d9c commit b648597
Showing 1 changed file with 8 additions and 16 deletions.
24 changes: 8 additions & 16 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,34 +218,26 @@ function remove(element: Element): boolean {
* Events
*/

function off(
element: Element,
eventTypes: EventTypes,
listener: EventListener
): void {
eventTypes.split(" ").forEach(eventType => {
element.removeEventListener(eventType, listener);
});
}

function on(
element: Element,
eventTypes: EventTypes,
listener: EventListener
): () => void {
const events = eventTypes.split(" ");
const offs = eventTypes.split(" ").map(eventType => {
element.addEventListener(eventType, listener);

events.forEach(eventType => element.addEventListener(eventType, listener));
return () => element.removeEventListener(eventType, listener);
});

return () => events.forEach(eventType => off(element, eventType, listener));
return () => offs.forEach(off => off());
}

function once(
element: Element,
eventTypes: EventTypes,
listener: EventListener
): () => void {
const offListeners = eventTypes.split(" ").map(eventType => {
const offs = eventTypes.split(" ").map(eventType => {
const wrappedListener = event => {
element.removeEventListener(eventType, wrappedListener);

Expand All @@ -254,10 +246,10 @@ function once(

element.addEventListener(eventType, wrappedListener);

return () => off(element, eventType, wrappedListener);
return () => element.removeEventListener(eventType, wrappedListener);
});

return () => offListeners.forEach(offListener => offListener());
return () => offs.forEach(off => off());
}

/*
Expand Down

0 comments on commit b648597

Please sign in to comment.