车把编译错误

Handlebars compile error

我使用 handlebars 生成这样的 tableview 模板:

模板

<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);

该脚本在第一个 运行 上运行良好。当我在表单中输入数据并点击提交按钮时,tableview 会平滑地显示来自数据库的数据。

当我输入其他数据并第二次点击提交按钮时,出现以下错误:

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

#incidentTemplate 如何在第二次尝试时破坏流程?有什么方法可以确保在加载所有内容时进行编译?

How does the #incidentTemplate corrupts the flow on the second attempt?

因为在第一个 post 之后,您将在此处用已编译的 html 替换模板:

 $('#incidentTableView').replaceWith($(this).createIncidentTableView(data));

将您的模板放在 #incidentTableView div.

之外的某个地方

此外,replaceWith 将替换当前匹配的元素,因此您将使用第一个 post 上的上述代码从 DOM 中删除 #incidentTableView。您将需要 div 在随后的 post 中存在,因此您需要执行以下操作:

$('#incidentTableView').html($(this).createIncidentTableView(data));