2.0.2 • Published 5 years ago

city-state v2.0.2

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

city-state.js

Observable and encapsulated state management

Installation

npm install --save city-state

Usage

<Subscribe> component

Subscribes to an Observable (like a subscribable) and updates children whenever there is a new value.

//
// 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 }) {
  <Subscribe to={[counter]}>
    {(counter) => (
      <span>Counter: {counter.count}</span>
    )}
  </Subscribe>
}

Redux offers an Observable API that could be used with Subscribe.

function CounterView({ reduxStore }) {
  <Subscribe to=[reduxStore]>
    {currentState => (
      <span>Counter: {currentState.count}</span>
    )}
  </Subscribe>
}

For a working example, see the code on /examples

@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
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)
}) // => 0

counter.increment() // => 1
counter.increment() // => 2
counter.decrement() // => 1

devtool()

Plot current state of a subscribable object (or any Observable) in Redux devtools.

@subscribable
class Foo {}

const foo = new Foo()

devtool(foo, { name: 'foo' })

Related

Sponsor

If you found this library useful and are willing to donate, transfer some bitcoins to 1BqqKiZA8Tq43CdukdBEwCdDD42jxuX9UY.

Credits


caiogondim.com  ·  GitHub @caiogondim  ·  Twitter @caio_gondim

2.0.2

5 years ago

2.0.1

5 years ago

1.1.3

5 years ago

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago