Skip to content

Commit

Permalink
Move delegate to events namespace
Browse files Browse the repository at this point in the history
  • Loading branch information
demiazz committed May 4, 2017
1 parent 385700e commit 2e4c875
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 35 deletions.
2 changes: 1 addition & 1 deletion spec/delegate.spec.js → spec/events/delegate.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { delegate } from "../src";
import { delegate } from "../../src";

describe("delegate", () => {
afterEach(clearFixtures);
Expand Down
41 changes: 41 additions & 0 deletions src/events/delegate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/* @flow */

import type { EventListener, EventType, Selector } from "../types";

import matches from "../traversing/matches";
import parent from "../traversing/parent";

function delegate(
element: Element,
selector: Selector,
eventType: EventType,
listener: EventListener
): () => void {
function wrappedListener(event) {
if (!(event.target instanceof Element)) {
return;
}

let current = event.target;

while (current) {
if (matches(current, selector)) {
listener(event);

return;
}

if (current === element) {
return;
}

current = parent(current);
}
}

element.addEventListener(eventType, wrappedListener);

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

export default delegate;
36 changes: 2 additions & 34 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
/* @flow */

import type { EventListener, EventType, Selector } from "./types";
import type { EventType, Selector } from "./types";

import { html, body } from "./aliases";
import addClass from "./css/add-class";
import hasClass from "./css/has-class";
import removeClass from "./css/remove-class";
import toggleClass from "./css/toggle-class";
import delegate from "./events/delegate";
import on from "./events/on";
import once from "./events/once";
import query from "./queries/query";
Expand Down Expand Up @@ -116,39 +117,6 @@ function remove(element: Element): boolean {

/* Events */

function delegate(
element: Element,
selector: Selector,
eventType: EventType,
listener: EventListener
): () => void {
function wrappedListener(event) {
if (!(event.target instanceof Element)) {
return;
}

let current = event.target;

while (current) {
if (matches(current, selector)) {
listener(event);

return;
}

if (current === element) {
return;
}

current = parent(current);
}
}

element.addEventListener(eventType, wrappedListener);

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

function dispatch(
element: Element,
eventType: EventType,
Expand Down

0 comments on commit 2e4c875

Please sign in to comment.