-
Notifications
You must be signed in to change notification settings - Fork 8
Observe
James edited this page Jun 24, 2017
·
3 revisions
👂 Observe
🎼
subscribe to changes
❗ called only on change observers are only called when data they subscribe to changes
type Matchable = string | 'globstring*' | 'dot.prop*' | RegExp | Function
class ObserveChain extends Composable, Chain {
public observe(properties: Matchable, onChange: Function): ChainAble
}
const log = arg => console.log(arg)
chain = Chain.init()
.observe('eh', data => log(data.eh === true))
.set('eh', true)
chain
.extend(['canada', 'timbuck'])
.observe(['canad*'], data => log(data.canada))
.canada(true)
.canada(true)
.timbuck(false)
const {Chain, eq} = require('chain-able')
const last = arr => arr.slice(0).pop()
class TodoStore extends Chain {
constructor(parent) {
super(parent)
this
.set('todos', [])
.methods(['completed', 'pending', 'total']).autoIncrement().build()
.observe('todos', ({todos}) => {
this.total(+1)
if (last(todos).completed) this.completed(+1)
else this.pending(+1)
})
}
// is verbose for clarification, could just
// return this.merge('todos', [{task, completed}])
add(task, completed = false) {
const todo = {task, completed}
const todos = this.get('todos').concat([todo])
return this.set('todos', todos)
}
}
const chain = new TodoStore()
chain
.add({eh: true})
.add({moose: 'eh!'}, true)
const entries = chain.entries()
const expected = {
todos: [
{task: {eh: true}, completed: false},
{task: {moose: 'eh!'}, completed: true},
],
completed: 1,
pending: 2,
total: 3,
}
eq(entries, expected)
- code
- tests
- extends ChainedMap
- extends DotProp
- https://github.com/mobxjs/mobx/blob/master/src/core/observable.ts
- https://github.com/ReactiveX/rxjs/blob/master/src/Subscriber.ts
- https://github.com/sindresorhus/awesome-observables
- https://medium.com/@benlesh/learning-observable-by-building-observable-d5da57405d87