0

我想從ajax調用(它提供了我需要的JSON)觸發的函數中使用underscore.js呈現模板成功。Underscore.js - 模板不能在第一時間編譯

我遇到了一些奇怪的現象:

  • 當AJAX調用成功,第一次,我得到這個錯誤:

Uncaught ReferenceError: response is not defined

  • 當它成功了第二次,沒有刷新頁面,一切都按預期進行。

我的JSON具有這樣的結構:

{ 
    data: [ 
     item1: {count: "1", url: "http://example1.com", id:"arstd", formatted:"1"}, 
     item2: {count: "53", url: "http://example2.net", id:"hneio", formatted:"0"}, 
     ... 
    ] 
} 

我underscore.js模板:

<script type="text/template" id="count_template"> 
    <% _.each (response.data, function (item) { %> 
    <a href="<%- item.url %>"> 
     <li> 
      <p id="<%- item.id %>" class="name"> 
       <%- item.formatted %> 
      </p> 
      <p id="<%- item.id %>_count" class="count"> 
       <%- item.count %> 
      </p> 
     </li> 
    </a> 
    <% }); %> 
</script> 

我的AJAX回調函數:

var on_result_count_fetched = (function() { 
    var totals = $(".regions .count"); 
    var ajax_loader = $("#ajax_loader"); 
    var c_tl = $('#count_template'); 
    var count_div = $('#res_count'); 
    //getting the template for the count response 
    if (c_tl) { 
     var c_template = _.template(c_tl.html()); 
    } 
    _.templateSettings.variable = "response"; 
    //real callback 
    return function (response) { 
     if (response.redirect) { 
      window.location.replace(data.redirect); 
     } else { 
      //hide loading animation 
      ajax_loader.hide(); 
      if (!response && _.isEmpty(response)) { 
       var tmp = $("<button>In case of fail: do this other action!</button>") 
       tmp.click (function() { 
        fetch_results ("searx"); 
       }); 
      } else { 
       console.log(response); 
       var tmp = c_template(response); 
      } 
      count_div.empty(); 
      count_div.append(tmp); 
     } 
    } 
}()); 

回答

0

當你說_.template(some_string),下劃線將使用的值解析some_string並將其轉換爲JavaScript函數。一旦_.template已向您返回已編譯的模板函數,_.templateSettings的內容就不再重要。

你做這樣的事情:

var t = _.template(some_string); 
_.templateSettings.variable = "response"; 

所以你_.templateSettings.variable分配來得太晚而影響您的_.template電話。您需要調用_.template所以在此之前調整_.templateSettings

if (c_tl) { 
    var c_template = _.template(c_tl.html()); 
} 
_.templateSettings.variable = "response"; 

應該更像:

if (c_tl) { 
    _.templateSettings.variable = "response"; 
    var c_template = _.template(c_tl.html()); 
} 

或者你可以完全跳過_.templateSettings說:

var tmp = c_template({ response: response }); 

致電時模板功能。如果您的其他模板不希望使用response來訪問其數據,則可能會產生副作用_.templateSettings。完全在一個地方全局配置_.templateSettings,或者完全保留一個地方往往效果更好。