Reputation: 3255
I use handlebars to generate a tableview template like this:
Template
<div id="incidentTableView">
<script id="incidentTemplate" type="text/x-handlebars-template">
<table class="table">
<thead>
<th>Latitude</th>
<th>Longitude</th>
</thead>
<tbody>
{{#incidents}}
<tr>
<td>{{Latitude}}</td>
<td>{{Longitude}}</td>
</tr>
{{/incidents}}
</tbody>
</table>
</script>
</div>
JavaScript
$(document).ready(function () {
$('#incidentForm').submit(function(e){
e.preventDefault();
var incidentLatitudeValue = $('#incidentLatitude').val();
var incidentLongitudeValue = $('#incidentLongitude').val();
$.post('ajax/test.php',
{
inputLatitude: incidentLatitudeValue,
inputLongitude: incidentLongitudeValue
},
function(data){
$('#incidentTableView').replaceWith($(this).createIncidentTableView(data));
},
"json");
});
});
(function($){
$.fn.createIncidentTableView = function(data){
var source = $("#incidentTemplate").html();
var template = Handlebars.compile(source);
var context = {
incidents: $.parseJSON(data)
}
return template(context);
};
})(jQuery);
The script works fine on the first run. When I enter data into the form and hit the submit button the tableview appears smoothly showing data from the database.
When I then input other data and hit the submit button the second time, the following error occurs:
XHR finished loading: POST "http://api.url.com/public/ajax/test.php".
handlebars-v3.0.0.js:2381 Uncaught Error: You must pass a string or Handlebars AST to Handlebars.compile. You passed undefined
How does the #incidentTemplate corrupts the flow on the second attempt? Is there a way how I can make sure the compiling takes place when everything is loaded?
Upvotes: 0
Views: 1787
Reputation: 26992
How does the #incidentTemplate corrupts the flow on the second attempt?
Because after the first post
you are replacing the template with the compiled html here:
$('#incidentTableView').replaceWith($(this).createIncidentTableView(data));
Place your template somewhere outside of the #incidentTableView
div
.
Also, replaceWith
will replace the current matched element so you'll be removing #incidentTableView
from the DOM with the above code on the first post
. You'll need that div
to be around for subsequent post
s so you'll want to do something like the following instead:
$('#incidentTableView').html($(this).createIncidentTableView(data));
Upvotes: 1