EMBER WORKSHOP: 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 jdcravens

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 players}}
        <li {{bindData this}}>{{name}}</li>
    {{/each}}
</ul>
</script>

CSS

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= {
  players: [
      {
          name: 'CrafterJohn',
          status: {isActive: true, isOnline: true} 
      },
      {
          name: 'MinerPaul', 
          status: {isActive: true, isOnline: false} 
      },
      {
          name: 'ExplorerRingo',
          status: {isActive: false, isOnline: false}
      }          
  ]
};

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