Reputation: 6060
I've recently started to use Handlebars.js and so far I'm loving it!
On my current project, I'm storing a bunch of literal values in data
attributes. I'm wondering if there is a way store the full JSON object in a tag for later use.
Current
{{#each this}}
<tr data-id="{{Id}}"
data-prod-code="{{ProductCode1}}"
data-gague="{{Gague}}"
data-rvalue="{{RValue}}"
data-density="{{Density}}"
data-fhaclass="{{FHAClass}}"
data-yards="{{Yards}}"
data-netting="{{Netting}}"
data-film="{{Film}}"
data-compressed="{{Compressed}}"
data-color="{{Color}}"
data-cfd="{{CFD}}"
data-elongation="{{Elongation}}"
data-tensilestrength="{{TensileStrength}}"
data-compressionset="{{CompressionSet}}"
data-title="{{Title}}">
<td>{{ProductCode1}}</td>
<td>{{Title}}</td>
<td>{{Gague}}</td>
</tr>
{{/each}}
Desired
{{#each this}}
<tr data-id="{{Id}}"
data-object="{{FULL JSON for current object in iteration}}">
<td>{{ProductCode1}}</td>
<td>{{Title}}</td>
<td>{{Gague}}</td>
</tr>
{{/each}}
Just in case it is relevant...
The data is returned from an MVC4 action and is called from a $.get()
request.
The reason I am wanting to do this is so that I can use a separate Handlebars template without the need to rebuild the data from the data
attributes.
In another post on here they recommended using jQuery to store the data in it's internal K,V pair. Unless it has some wicked cleanup ability that I'm not aware of I'm going to avoid this so that it's memory usage doesn't skyrocket. The data that is stored in the data
attributes is swapped out quite frequently based on a search term so I don't want it stored in the jQuery object (unless this is a 100% unfounded concern).
Upvotes: 1
Views: 1043
Reputation: 6060
SOLUTION:
I ended up needing to make a Handlebars
helper.
Handlebars.registerHelper('getObjectJSON', function() {
return JSON.stringify(this);
});
Then my Handlebars
template looked like this...
<script id="product-row-template" type="text/x-handlebars-template">
{{#each this}}
<tr data-id="{{Id}}"
data-title="{{Title}}"
data-productcode1="{{ProductCode1}}"
data-object='{{getObjectJSON}}'>
<td class="addProductToCart">{{ProductCode1}}</td>
<td class="addProductToCart">{{Title}}</td>
<td class="addProductToCart">{{Gague}}</td>
<td class="viewProductDetail" style="width: 5%"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></td>
</tr>
{{/each}}
</script>
This allowed me to pass that data object to other Handlebars
templates for use in modals/etc...
$("#modalBodyAndFooter").html(marketingModalTemplate($(this).closest("tr").data("object")));
Upvotes: 1