-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(events): Switch to event delegation
This switches to using event delegation and filtering of the event source to allow things to continue to work under the same semantics, but greating reducing the cost of the operation. References #4
- Loading branch information
Showing
1 changed file
with
38 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,43 @@ | ||
import {empty} from 'most' | ||
import fromEvent from './fromEvent' | ||
import {makeIsStrictlyInRootScope} from './select' | ||
|
||
const makeEventsSelector = | ||
element$ => | ||
(type, useCapture = false) => { | ||
if (typeof type !== `string`) { | ||
throw new Error(`DOM drivers events() expects argument to be a ` + | ||
`string representing the event type to listen for.`) | ||
} | ||
return element$ | ||
.map( | ||
elements => | ||
elements ? | ||
fromEvent(type, elements, useCapture) : | ||
empty() | ||
) | ||
.switch() | ||
.multicast() | ||
let matchesSelector | ||
try { | ||
matchesSelector = require(`matches-selector`) | ||
} catch (err) { | ||
matchesSelector = () => {} | ||
} | ||
|
||
function makeEventsSelector(element$, selector) { | ||
return function eventsSelector(type, useCapture = false) { | ||
if (typeof type !== `string`) { | ||
throw new Error(`DOM drivers events() expects argument to be a ` + | ||
`string representing the event type to listen for.`) | ||
} | ||
return element$ | ||
.map(elements => { | ||
if (!elements) { | ||
return empty() | ||
} | ||
|
||
if (matchesSelector(elements, selector.join(` `))) { | ||
return fromEvent(type, elements, useCapture) | ||
} | ||
|
||
return fromEvent(type, elements, useCapture) | ||
.filter(ev => { | ||
if (matchesSelector(ev.srcElement, selector.join(` `)) || | ||
matchesSelector(ev.srcElement, selector.join(``))) | ||
{ | ||
return makeIsStrictlyInRootScope(selector)(ev.srcElement) | ||
} | ||
return false | ||
}) | ||
}) | ||
.switch() | ||
.multicast() | ||
} | ||
} | ||
|
||
export {makeEventsSelector} | ||
export default makeEventsSelector |