2 way binding with watch.js
HTML
<script src="http://www.danshahin.com/watch.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script>
<input class="bound" id="name" placeholder="name" />
<input class="bound" id="rank" placeholder="rank" />
<input class="bound" id="serial" placeholder="serial" />
<div id="person"/>
<script id="person-template" type="text/x-handlebars-template">
</br>
<input class="bound" id="{{name}}" placeholder="name" value={{name}}/>
<input class="bound" id="{{rank}}" placeholder="rank" value={{rank}}/>
<input class="bound" id="{{serial}}" placeholder="serial" value={{serial}}/>
<table class="person">
<tr>
<th>name</th> <th>rank</th> <th>serial</th>
</tr>
<tr>
<td>{{name}}</td> <td>{{rank}}</td> <td>{{serial}}</td>
</tr>
</table>
</script>
CSS
input{
width:30vw;
height: 10vh;
font-size: 7vh;
}
table.person{
width: 100%;
background-color: tan;
font-size: 5vw;
}
table.person tr td {
background-color: lightblue;
padding:2px;
}
JavaScript
//use single var for scope
var $scope = {
template : Handlebars.compile( $("#person-template").html() )
}
//method to draw table
$scope.render = function() {
var html = $scope.template($scope.person)
$('#person').html(html);
}
//setup object
$scope.person = {
name: "dan",
rank: "captain",
serial: 123
}
//match ui to person object
for(prop in $scope.person){
$('#'+prop).val($scope.person[prop]);
}
//draw the table
$scope.render();
//bind UI elements to object with jquery
$('body').on('keyup', 'input.bound', function () {
//update model with
var input = $(this);
prop = input.attr('id');
$scope.person[prop] = $(this).val();
}).on('change', '.bound', function () {
//this is where you might save to the server
console.log($scope.person);
});
//bind object to UI elements with watch.js
watch($scope, function (prop, action, newvalue, oldvalue) {
console.log(prop, action, ' was ', oldvalue, ' is ', newvalue);
// $('#' + prop).val(newvalue);
//redraw table
$scope.render();
});
//wait 2 seconds and extend properties on person
setTimeout(
function(){
$.extend($scope.person, {name:'freddy', rank: 'general', serial: '1234567'});
}, 2000);