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 Durtto

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="people-template">
<ul>
    {{#each people}}
        <li {{bindData this}}>{{name}}</li>
    {{/each}}
</ul>
</script>

CSS

body {
    padding: 10px;
}

li {
    cursor: pointer;
}

li:hover {
    text-decoration: underline;
}

JavaScript

(function() {

    var id = 0,
        cache = [];
        
    Handlebars.registerHelper("bindData", function(data) {
        var dataKey = id++;
        cache[dataKey] = data;

        return "data-handlebar-id=" + dataKey;
    });

    Handlebars.getBoundData = function(handlebarId) {
        if (typeof(handlebarId) !== "string") {
            // If a string was not passed in, it is the html element, so grab it's id.
            handlebarId = handlebarId.getAttribute("data-handlebar-id");
        }

        return cache[handlebarId];
    };
    
})();

var context= {
  people: [
    { name: "John Doe", location: { city: "Chicago" } },
    { name: "Jane Doe", location: { city: "New York"} }
  ]
};

var template = Handlebars.compile($("#people-template").text());
var html = template(context);
$(document.body)
    .html(html)
    .on("click", "li", function() {
        var boundData = Handlebars.getBoundData(this);
        alert(JSON.stringify(boundData));
    });