https://github.com/caiogondim/city-state.js
:crown: Observable and encapsulated state management
https://github.com/caiogondim/city-state.js
Last synced: 2 months ago
JSON representation
:crown: Observable and encapsulated state management
- Host: GitHub
- URL: https://github.com/caiogondim/city-state.js
- Owner: caiogondim
- Created: 2018-05-14T20:11:08.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2019-07-09T02:51:07.000Z (almost 6 years ago)
- Last Synced: 2025-03-24T21:51:09.247Z (3 months ago)
- Language: JavaScript
- Homepage: https://npm.im/city-state
- Size: 912 KB
- Stars: 7
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# city-state.js
> Observable and encapsulated state management
## Installation
```bash
npm install --save city-state
```## Usage
### `` component
Subscribes to an Observable (like a [subscribable](#subscribable)) and updates
children whenever there is a new value.```js
//
// Model
//import { subscribable } from 'city-state'
@subscribable
class Counter {
constructor() {
this.count = 0
}increment() {
this.count += 1
}decrement() {
this.count -= 1
}
}const counter = new Counter()
//
// View
//import React from 'react'
import { Subscribe } from 'city-state'export default function CounterView({ counter }) {
{(counter) => (
Counter: {counter.count}
)}
}
```Redux offers an Observable API that could be used with `Subscribe`.
```js
function CounterView({ reduxStore }) {
{currentState => (
Counter: {currentState.count}
)}
}
```For a working example, see the code on [`/examples`](/examples/index.js)
### `@subscribable`
Adds a minimal Observable interface to a class.
Whenever a property is changed on the subscribable object, all subscribers are notified.Interface:
- `this.subscribe()`: Observable subscribe method
- `this[$$obseravble]`: Symbol.Observable interop point```js
import { subscribable } from 'city-state';@subscribable
class Counter {
constructor() {
this.count = 0
}increment() {
this.count += 1
}decrement() {
this.count -= 1
}
}const counter = new Counter()
counter.subscribe(() => {
console.log(counter.count)
}) // => 0counter.increment() // => 1
counter.increment() // => 2
counter.decrement() // => 1
```### `devtool()`
Plot current state of a subscribable object (or any Observable) in Redux devtools.
```js
@subscribable
class Foo {}const foo = new Foo()
devtool(foo, { name: 'foo' })
```## Related
- [city-state-preact](https://github.com/caiogondim/city-state-preact.js)## Sponsor
If you found this library useful and are willing to donate, transfer some
bitcoins to `1BqqKiZA8Tq43CdukdBEwCdDD42jxuX9UY`.## Credits
- Icon by Praveen Patchu from The Noun Project
- [Redux](https://github.com/reduxjs/redux)
- [Unstated](https://github.com/jamiebuilds/unstated)---
[caiogondim.com](https://caiogondim.com) ·
GitHub [@caiogondim](https://github.com/caiogondim) ·
Twitter [@caio_gondim](https://twitter.com/caio_gondim)