andrewvy / fad

:icecream: Framework-agnostic Data (Representation)
MIT License
2 stars 0 forks source link

Observables/Listener API #6

Open andrewvy opened 8 years ago

andrewvy commented 8 years ago
import fad from 'fad'

const Store = fad.createStore()
const Car = Store.createModel('car', {
  propTypes: {
    name: fad.PropTypes.string,
    type: fad.PropTypes.string,
    passengers: fad.PropTypes.number
  }
})

let car = new Car({
  name: 'Foo',
  type: 'Bar'
})

// reactive
let observer = car.observe('passengers')
  .filter((passengers) => passengers > 5)
  .result(() => {
    throw new Error('Car is full!')
  })

observer.dispose()

// traditional
const Listener = fad.createListener()
Listener.on(car, 'passengers', () => {
  let passengers = car.get('passengers')
  if (passengers > 5) throw new Error('Car is full!')
})
Listener.dispose()
andrewvy commented 8 years ago
const Store = fad.createStore()
const Post = Store.createModel('post', {
  propTypes: {
    name: fad.PropTypes.string,
    content: fad.PropTypes.string
  }
})

let blogPost = new Post()

let PostComponent = (props) => {
  <div className='post'>
    <div className='postTitle'>{props.post.title}</div>
    <div className='postContent'>{props.post.content}</div>
  </div>
}

let render = (post) => {
  ReactDOM.render(<PostComponent post={post} />, mountNode)
}

blogPost
  .stream('*')
  .subscribe(render)

blogPost.set('Hello world!')

An example w/ React stateless components.