Handlebars/Mustache Templating Example
Handlebars Template
<table class="table table-striped table-bordered table-responsive">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Full Name</td>
</tr>
</thead>
{{#people}}
<tr>
<td><input class="form-control" data-bindto="people[{{@index}}].firstName" value="{{firstName}}"></td>
<td><input class="form-control" data-bindto="people[{{@index}}].lastName" value="{{lastName}}"></td>
<td data-watching="people[{{@index}}].lastName,people[{{@index}}].firstName" data-parsewith="people[{{@index}}].fullName">{{fullName.in}}</td>
</tr>
{{/people}}
<tr>
<td colspan="4">
<button id="addRowBtn" class="btn btn-default">Add Row</button>
</td>
</tr>
</table>
JavaScript
$(function(){
var template='...'//template code can be seen above...
var mustache = Handlebars.compile(template);
var Person=function(firstName,lastName){
var Person=this;
Person.firstName=firstName;
Person.lastName=lastName;
Person.fullName={
in: function () {
var lastName = Person.lastName;
if (lastName.length > 0)
lastName = " " + lastName;
else
lastName = "";
return Person.firstName + lastName;
}
}
};
var model=[
new Person("Agatha", "Trunchbull"),
new Person("Jennifer", "Honey"),
new Person("Matilda", "Wormwood")
];
var $htmlDiv=$('#htmlDiv');
}());
GDB({people: model});
$('pre code#model').text(JSON.stringify(model, null, ' '));
$htmlDiv.html(mustache({people: model}));
$('#htmlCode').text($htmlDiv.html().trim());
$('body').on('click','#addRowBtn',function(){
model.push(new Person("", ""));
$htmlDiv.html(mustache({people: model}));
});
});