2011-11-07 51 views
3

有什麼辦法來編譯服務器獲得Closure編譯器與生成的代碼上工作Underscore.js模板?使用Closure編譯器與Underscore.js _.template

的主要問題是_.template

_.template = function(str, data) { 
    var c = _.templateSettings; 
    var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + 
     'with(obj||{}){__p.push(\'' + 
     str.replace(/\\/g, '\\\\') 
     .replace(/'/g, "\\'") 
     .replace(c.interpolate, function(match, code) { 
      return "'," + code.replace(/\\'/g, "'") + ",'"; 
     }) 
     .replace(c.evaluate || null, function(match, code) { 
      return "');" + code.replace(/\\'/g, "'") 
       .replace(/[\r\n\t]/g, ' ') + "__p.push('"; 
     }) 
     .replace(/\r/g, '\\r') 
     .replace(/\n/g, '\\n') 
     .replace(/\t/g, '\\t') 
     + "');}return __p.join('');"; 
    var func = new Function('obj', tmpl); 
    return data ? func(data) : func; 
}; 

生成JavaScript在它與語句。這兩個明顯的路線是:

  1. 修改Underscore.js的_.template不產生withs
  2. 要挾封蓋進入踢得好看

是第二個選項可能嗎?

回答

2

通常,JS引擎在沒有「with」的情況下執行得更好,所以如果在沒有「with」的情況下生成它是一種可能是最佳解決方案的選項。

否則您的選擇取決於您是否希望使用Closure Compilers ADVANCED模式。在SIMPLE模式下,編譯器不會重命名模板上的屬性,並假定任何未聲明的變量都是全局變量。所以只要你的模板對象不會導致任何局部變量被隱藏,它可能「正常工作」。

+0

是的,我的目標是進行高級編輯。我不願意修改_.template是因爲它是定期更新的庫代碼 - 一個維護問題。 – hughdbrown

+0

根據您的需求,您可能會考慮使用專用於ADVANCED編譯的Closure模板。 – John