object-observe

A simple two way binding with Object.observe

by Fatih Acet

HTML

<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css">
<div class="pure-form">
    <fieldset>
        <legend>Simple two way data binding with Object.observe</legend>
        <input type="text" id="input" placeholder="Type your name" /> or 
        <button id="button" class="pure-button pure-button-primary">Click here to update name in the model</button>
        <p id="label"></p>
    </fieldset>
</div>

CSS

body { margin: 10px; }

CoffeeScript

input  = document.getElementById 'input'
label  = document.getElementById 'label'
button = document.getElementById 'button'
model  = {}

updateLabel = (name) ->
    label.innerHTML = "My name is #{name}"

input.addEventListener 'keyup', ->
    model.name = input.value
    
button.addEventListener 'click', ->
    model.name = 'John'

Object.observe model, (change) ->
    updateLabel change[0].object.name
    
model.name = 'Fatih'