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

0.2.5 • Public • Published

Build StatusGitHub licensecode style: prettier

babas

A tiny library for watching objects.

watch

Watching all Values

By default all values are watched:

import { watch } from 'babas'
 
const user = watch({ name: 'Bob', age: 25 })
 
user.subscribe((user, propName) => {
  console.log(`Updated ${propName} for user.`)
})
 
user.name = 'Bill' // User name updated
 
user.age = 26 // User age updated

Watching Specific Values

A subscription object can be passed as the second argument to restrict which properties should be watched.

import { watch } from 'babas'
 
const user = watch({ name: 'Bob', age: 25 })
 
user.subscribe(
  user => {
    console.log(`Happy Birthday ${user.name}, you're ${user.age} years old!`)
  },
  { age: true }
)
 
user.name = 'Bill'
 
user.age = 26 // Happy Birthday Bill, you're 26 years old!

Unsubscribe

import { watch } from 'babas'
 
const user = watch({ name: 'Bob', age: 25 })
 
const unsubscribe = user.subscribe(() => console.log('User updated'))
 
user.name = 'Bill' // User updated
 
unsubscribe()
 
user.age = 26

Unsubscribe Explicit

import { watch } from 'babas'
 
const user = watch({ name: 'Bob', age: 25 })
 
const onUserDidUpdate = () => console.log('User updated')
 
user.subscribe(onUserDidUpdate)
 
user.name = 'Bill' // User updated
 
user.unsubscribe(onUserDidUpdate)
 
user.age = 26

createCollection

Creating Collections

import { createCollection } from 'babas'
 
const bob = {
  name: 'Bob',
  age: 25,
}
 
const users = createCollection({ bob })

Subscribing and Unsubscribe

const unsubscribe = users.subscribe((users, { change, entry }) => {
  if (change === 'set') {
    console.log(`${entry.name} can come!`)
  } else {
    console.log(`${entry.name} can no longer attend :(`)
  }
 
  console.log(`There are now ${users.toArray().length} guests`)
})
 
unsubscribe()

Adding Entries

There are 2 ways to add entries:

user.janet = { name: 'Janet', age: 23 }
user['polly'] = { name: 'Polly', age: 54 }

Removing Entries

There are 2 ways to remove entries:

delete users.polly
delete users['bill']

Custom Collection Methods

import { createCollection } from 'babas'
 
const users = createCollection({}, collection => ({
  add(user) {
    return (collection[user.id] = user)
  },
  remove(user) {
    delete collection[user.id]
  },
}))
 
user.add({ id: 'janet', name: 'Janet', age: 23 }
user.add({ id: 'polly', name: 'Polly', age: 54 }

Thanks

This project was bootstrapped with TSDX.

Readme

Keywords

none

Package Sidebar

Install

npm i babas

Weekly Downloads

8

Version

0.2.5

License

MIT

Unpacked Size

41 kB

Total Files

17

Last publish

Collaborators

  • ncphillips