2.0.0 • Published 6 years ago

with-subscribe v2.0.0

Weekly downloads
1
License
MIT
Repository
-
Last release
6 years ago

with-subscribe

Minimal Observable interface to watch for object modifications.

Installation

npm install --save with-subscribe

Usage

On a constructor:

class Counter {
  constructor() {
    this.count = 0
  }

  increment() {
    this.count += 1
  }
}
const CounterWithSubscribe = withSubscribe(Counter)
const counter = new CounterWithSubscribe()

counter.subscribe(() => console.log('State:', counter.count)) // -> State: 0

counter.increment() // -> State: 1
counter.increment() // -> State: 2

As a decorator:

@withSubscribe
class Counter {
  constructor() {
    this.count = 0
  }

  increment() {
    this.count += 1
  }
}
const counter = new Counter()

counter.subscribe(() => console.log('State:', counter.count)) // -> State: 0

counter.increment() // -> State: 1
counter.increment() // -> State: 2

On an object:

const counter = withSubscribe({
  count: 0,
  increment() {
    this.count += 1
  }
})

counter.subscribe(() => console.log('State:', counter.count)) // -> State: 0

counter.increment() // -> State: 1
counter.increment() // -> State: 2

caiogondim.com  ·  GitHub @caiogondim  ·  Twitter @caio_gondim