observevent
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

Observevent

Event Observer inspired by svelte/store and rxjs

Installation

npm i observevent

Usage

subjectify

import { subjectify } from 'observevent'

const food = subjectify('')
const unsubscribe = food.subscribe((newValue, oldValue) => console.log(newValue, oldValue))
// or 
// food.subscribe((newValue) => console.log(newValue))

food.notify('apple')
food.notify((it) => it + ' pie')

unsubscribe()

// Output
// ----------
// '', undefined
// 'apple, '
// 'apple pie, apple'

observify

import { observify, select } from 'observevent'
import { EventEmitter } from 'events'

const emitter = new EventEmitter()

const logger = {
  info: (...args: unknown[]) => console.log('[food]', ...args)
}

function isPie(food: string): boolean {
  return food.indexOf('pie') > -1
}

const food = observify('', (trigger) => {
  emitter.on('food', trigger)
  return () => emitter.removeAllListener('food')
}, /** Option **/  { logging: true, logger })

const unsubscribe = select(food, isPie).subscribe((it) => it)

emitter.emit('food', 'apple')

unsubscribe()

// Output
// ----------
// '[food] "", undefined'
// '[food] "", apple'

Options

observify and subjectify and combine and combineMap have the following options:

logging

Setting logging to true will output changelog.
Default value is false.

import { subjectify } from 'observevent'

const food = subjectify('', { logging: true })
const unsubscribe = food.subscribe((it) => it)

food.notify('apple')
food.notify((it) => it + ' pie')

unsubscribe()

// Output
// ----------
// { before: undefined, after: '' }
// { before: '', after: 'apple' }
// { before: 'apple', after: 'apple pie' }

logger

You can set a custom logger.

import { subjectify } from 'observevent'

const logger = {
  info: (value: unknown) => console.log('[food]', value)
}

const food = subjectify('', { logging: true, logger })
const unsubscribe = food.subscribe((it) => it)

food.notify('apple')
food.notify((it) => it + ' pie')

unsubscribe()

// Output
// ----------
// [food] { before: undefined, after: '' }
// [food] { before: '', after: 'apple' }
// [food] { before: 'apple', after: 'apple pie' }

immediate

If immediate is set to false, the current value will not be notified and will be notified from changes after subscription.
Default value is true.

import { subjectify } from 'observevent'

const food = subjectify('', { immediate: false })
const unsubscribe = food.subscribe((it) => console.log(it))

food.notify('apple')
food.notify((it) => it + ' pie')

unsubscribe()

// Output
// ----------
// 'apple'
// 'apple pie'

Derives

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.1
    1
    • latest

Version History

Package Sidebar

Install

npm i observevent

Weekly Downloads

11

Version

1.0.1

License

MIT

Unpacked Size

37 kB

Total Files

19

Last publish

Collaborators

  • koheing