Accessing bound data with Handlebars
An example showing how to access the data that was bound to a specific element that was generated via a Handlebars template.
by creed88
HTML
<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.4.js"></script>
<script type="text/x-handlebars" id="your-template">
{{#each products}}
{{groupData this}}
{{/each}}
{{#each cache}}
<ul id="area-{{id}}">
{{#each products}}
<li id="{{sn}}">{{name}}</li>
{{/each}}
</ul>
{{/each}}
</script>
CSS
body {
padding: 10px;
}
li {
cursor: pointer;
}
li:hover {
text-decoration: underline;
}
JavaScript
(function() {
var id = 0,
cache = [];
var ids={};
Handlebars.registerHelper("groupData", function(products) {
var dataKey = id++;
ids[products.pclass]=true;
if(cache[products.pclass]==undefined) cache[products.pclass]={id:products.pclass, products:[products]};
else cache[products.pclass].data.push(products)
if(dataKey==context.products.length-1){
context.cache=[];
for(var i in ids){
context.cache.push(cache[i])
}
}
});
})();
var context={"products":[
{ "sn":"43","pclass":"3","name":"X1","status":"empty","seats":"12"},
{ "sn":"22","pclass":"1","name":"F1","status":"empty","seats":"8"},
{ "sn":"12","pclass":"2","name":"E1","status":"empty","seats":"6"},
{ "sn":"18","pclass":"3","name":"R3","status":"empty","seats":"6"},
{ "sn":"31","pclass":"1","name":"G4","status":"empty","seats":"4"},
{ "sn":"23","pclass":"2","name":"W5","status":"empty","seats":"12"}
]}
var template = Handlebars.compile($("#your-template").text());
var html = template(context);
document.body.innerHTML=html;