Skip to content

Commit

Permalink
feat(global): add scroll event publish helper function
Browse files Browse the repository at this point in the history
  • Loading branch information
colinmeinke committed Feb 24, 2017
1 parent c6b9d2e commit 67a6815
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 4 deletions.
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
A simple publish/subscribe pattern

- Plain old vanilla JS
- Just 1kb gzipped
- Just 1.2kb gzipped

## Installation

Expand Down Expand Up @@ -76,6 +76,20 @@ event.subscribe('global.escape', () => {
})
```

#### Scroll

```js
import Event, { publishScroll } from 'core-events'

const event = new Event()

publishScroll({ event })

event.subscribe('global.scroll', ({ direction, speed }) => {
console.log(`Somebody scrolled ${direction} at ${speed} px per ms`)
})
```

#### Swipe

```js
Expand Down
9 changes: 7 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { publishClick, publishEscape, publishSwipe } from './publish'
import {
publishClick,
publishEscape,
publishScroll,
publishSwipe
} from './publish'

const _ = new WeakMap()

Expand Down Expand Up @@ -46,6 +51,6 @@ class Event {
}
}

export { publishClick, publishEscape, publishSwipe }
export { publishClick, publishEscape, publishScroll, publishSwipe }

export default Event
24 changes: 23 additions & 1 deletion src/publish.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,28 @@ const publishEscape = ({ event, name = 'global.escape' }) => {
})
}

const publishScroll = ({ event, limit = 10, name = 'global.scroll' }) => {
let lastPosition = 0
let lastTime = 0

window.addEventListener('scroll', () => {
const currentPosition = window.scrollY
const currentTime = Date.now()
const time = currentTime - lastTime

if (lastTime && time >= limit) {
const direction = currentPosition > lastPosition ? 'down' : 'up'
const distance = Math.abs(lastPosition - currentPosition)
const speed = distance / time

event.publish(name, { direction, speed })
}

lastTime = currentTime
lastPosition = currentPosition
})
}

const publishSwipe = ({
event,
name = 'global.swipe',
Expand Down Expand Up @@ -65,4 +87,4 @@ const publishSwipe = ({
window.addEventListener('mouseup', e => swipeEnd(e))
}

export { publishClick, publishEscape, publishSwipe }
export { publishClick, publishEscape, publishScroll, publishSwipe }

0 comments on commit 67a6815

Please sign in to comment.