https://github.com/renddslow/state-watcher
A lightweight browser state built with proxies inspired by reactivity
https://github.com/renddslow/state-watcher
Last synced: 2 months ago
JSON representation
A lightweight browser state built with proxies inspired by reactivity
- Host: GitHub
- URL: https://github.com/renddslow/state-watcher
- Owner: Renddslow
- License: other
- Created: 2019-11-22T04:33:07.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-07-10T04:19:50.000Z (almost 2 years ago)
- Last Synced: 2025-02-21T12:40:44.441Z (3 months ago)
- Language: JavaScript
- Homepage:
- Size: 573 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 6
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE.md
Awesome Lists containing this project
README
# State Watcher
> A light-weight local browser state build on the subscriber pattern.
## Install
```
$ yarn add state-watcher
```## Usage
```js
import createState from 'state-watcher';const [state, watcher] = createState({
playerName: '',
score: 0,
});watcher.on('change', ['score'], (state, score) => {
document.getElementById('score-container').innerText = score;
});watcher.on('change', ['playerName'], (state, name) => {
document.getElementById('player-name-container').innerText = name;
});function updatePlayerScore(score) {
state.score = score;
}function updatePlayerName({ target }) {
state.playerName = target.value || '';
}
```## API
### createState(obj)
Returns a tuple with the state object and a [watcher](#watcher).
#### obj
Type: `object`
Default: `{}`
A plain-old JavaScript object that will serve as the default state.
### watcher
Type: `object`
An object containing an `on`, `has`, and `keys` method.
#### on(type, ?fields, cb)
##### type
Type: `string`
A string that indicates which event should be subscribed to on the watcher. Currently only `"change"` is supported.
##### fields
Type: `Array`
Optional: ✅
An array of strings indicating which field(s) the callback should subscribe to on the specified event. When no fields are passed in, all fields for the given event will fire the callback.
##### cb(state, value, key)
Type: `function`
A callback that is fired when an event of `type` occurs to the specified (or all) fields.