Reactive.JS and D3

by ramnathv

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.min.js"></script>
<script src="//rawgit.com/mattbaker/Reactive.js/master/src/reactive.js"></script>
<script src="//rawgit.com/mattbaker/Reactive.js/master/src/reactive.dom.js"></script>
<script src="//d3js.org/d3.v3.min.js"></script>
<div id="box"></div>
<input id='input' type="text" placeholder='Enter Something'> </input>
<input type="range" min="0" max="10" value="1" id="fader">
<span id="news">Hello</span>

CSS

#box{
    width: 300px;
    height: 300px;
}

CoffeeScript

# hack bindToInput to support generic events
$R.extend($R.pluginExtensions, {
    bindToInput: (input, event) ->
      if arguments.length is 1
        console.log event
        event = 'change'
      rf = this
      $(input).on event, ->
        rf(this.value);
      return this
});

# MODEL
model = 
  color: $R((x) -> x).bindToInput("#input", "keyup")
  opacity: $R((x) -> x/10).bindToInput("#fader")
  
# VIEW
view = $R((x, o) ->
  d3.select('#box')
   .style('background', x)
   .style('opacity', o)
)

# bind view to model
view.bindTo.apply(view, d3.values(model))

    
###
qs = (x) -> document.querySelector(x)
$input = qs("#input")

keyups = Rx.Observable.fromEvent($input, 'keyup')
  .map((e) -> e.target.value)
  .debounce(500)
  .distinctUntilChanged()
    
keyups.subscribe(
 (x) -> 
  console.log(x)
  #d3.select("body").style('background', x)
)

myInput = (sel, state, fn) ->
  y = $R.state(state)
  d3.select(sel).on "change", ->
    v = @value
    if typeof fn is 'function'
      y.set(fn(v))
    else
      y.set(v)
  y
###