EventBeat
![npm](https://img.shields.io/npm/v/eventbeat.svg)
EventBeat is a declarative subscription layer for managing global event handlers such as mouse/keyboard events and custom data streams like time interval events, geolocation changes, WebSocket messages, etc.
Getting Started
Here is a minimal example to get you started. Go ahead and try it online.
import { applyToAction } from "eventbeat"
const listen = applyToAction(console.log)
listen([
{
type: "mousemove",
action: event => `${event.x} ${event.y}`
},
{
type: "keydown",
action: event => `${event.key}:${event.keyCode}`
}
])
We want to be notified when something happens in the outside world, e.g., mouse movements, keyboard presses, clock ticks, browser repaints, and so on.
Subscriptions allow us to listen for such things. A subscription is a plain JavaScript object that identifies the event type you want to listen to and an action to call with the event. See Creating Custom Subscriptions for advanced usage.
To listen to or cancel subscriptions you need a listen
function which you can get through applyToAction(handler)
. EventBeat will invoke the handler
with the result of every delivered action. Actions turn events into data and handler
encapsulates side effects like drawing on the screen or relaying messages to a Redux store, etc.
In the previous example we logged every message to the console. Next we'll use a custom handler function to draw some gradients. Try it online.
import { applyToAction } from "eventbeat"
const render = state => {
document.body.style.background = `
transparent
radial-gradient(
at calc(${state.x} * 100%) calc(${state.y} * 100%),
cyan,
blue
) no-repeat fixed center
`
}
const listen = applyToAction(render)
listen([
{
type: "mousemove",
action: event => ({
x: event.clientX / event.view.innerWidth,
y: event.clientY / event.view.innerHeight
})
}
])
Installation
Install with npm or Yarn.
npm i eventbeat
Then with a module bundler like Rollup or Webpack, use as you would anything else.
import { applyToAction } from "eventbeat"
Don't want to set up a build environment? Download EventBeat from a CDN like unpkg.com and it will be globally available through the window.eventbeat
object. All ES5-compliant browsers, including IE 9 and up are supported.
<script src="https://unpkg.com/eventbeat"></script>
Overview
Creating Custom Subscriptions
Links
License
EventBeat is MIT licensed. See LICENSE.