@reatom/web
TypeScript icon, indicating that this package has built-in type declarations

3.5.1 • Public • Published

This package exposes a set of handy bindings to browser APIs.

Installation

npm i @reatom/web

onEvent

The onEvent function enables you to respond to various types of events for the target element that supports the addEventListener interface, such as HTMLInputElement or WebSocket, among others.

You can pass a callback as the last argument. In this case, the method will return an unsubscribe function. If you skip the callback, the returned value will be a promise that will resolve with the event.

Please note that this API handles the abort context from the onConnect effect and other Reatom APIs. It enables you to describe complex logic in a concise and clear manner with memory safety underneath.

Here is a usage example, which was revrited from this observable example:

import { atom, onConnect, onCtxAbort } from '@reatom/framework'
import { onEvent } from '@reatom/web'

const socket = new WebSocket('wss://example.com')

const reatomStock = (ticker) => {
  const stockAtom = atom(null, `${ticker}StockAtom`)
  onConnect(stockAtom, async (ctx) => {
    if (socket.readyState !== WebSocket.OPEN) {
      await onEvent(ctx, socket, 'open')
    }
    socket.send(JSON.stringify({ ticker, type: 'sub' }))
    onEvent(ctx, socket, 'message', (event) => {
      if (event.data.ticker === ticker) stockAtom(ctx, JSON.parse(event.data))
    })
    onEvent(ctx, socket, 'close', () => ctx.controller.abort())
    onEvent(ctx, socket, 'error', () => ctx.controller.abort())
    onCtxAbort(ctx, () =>
      socket.send(JSON.stringify({ ticker, type: 'unsub' })),
    )
  })

  return stockAtom
}

const googStockAtom = reatomStock('GOOG')

ctx.subscribe(googStockAtom, updateView)

Package Sidebar

Install

npm i @reatom/web

Weekly Downloads

81

Version

3.5.1

License

MIT

Unpacked Size

53.3 kB

Total Files

12

Last publish

Collaborators

  • artalar