4

我一直在使用Typeahead 0.9.3和Hogan 2一段時間,這是非常簡單的設置。用Hogan遷移到Typeahead 0.10+

在0.9.3

我不喜歡的東西:

$('input.search-query').typeahead([ 
    { 
     name:  "pages" 
     ,local: localSuggestions 
     ,template: '<div class="tt-suggest-page">{{value}}</div>' 
     ,engine: Hogan 
    } 
]); 

按照Migration Guide to 0.10 「預編譯模板現在需要」,所以在0.10.3我想:

$('input.search-query').typeahead(null, { 
    name:  "pages" 
    ,source: taSourceLocal.ttAdapter() 
    ,templates: { 
     suggestion: Hogan.compile('<div class="tt-suggest-page">{{value}}</div>') 
    } 
}); 

但這是行不通的。我得到一個錯誤:Uncaught TypeError: object is not a function

如果有另一個可以工作的極簡主義模板引擎,我會考慮它,但它必須很小。我不想添加像Handlebars這樣的大文件或像Underscore這樣的整個庫。

有什麼想法? TIA!

回答

9

如前所述由傑克·哈丁,the solution for modern browsers是像這樣:

var compiledTemplate = Hogan.compile('<div class="tt-suggest-page">{{value}}</div>'); 

$('input.search-query').typeahead(null, { 
    // ... 
    templates: { 
     suggestion: compiledTemplate.render.bind(compiledTemplate); 
    } 
}); 

不幸的是,Function.prototype.bind() is not supported by IE < 9,所以如果你需要支持舊版本瀏覽器將無法正常工作。

好消息是as stated by Steve Pavarno你不需要模板引擎了。你可以通過傳遞函數像這樣達到預期的效果:

// ... 
    templates: { 
     suggestion: function(data) { // data is an object as returned by suggestion engine 
      return '<div class="tt-suggest-page">' + data.value + '</div>'; 
     }; 
    } 
+0

注意,上面列出的非模板引擎版本是不安全的,如果你的數據可以包含HTML特殊字符(例如<>「」&),你將需要 –

+0

非常感謝:) – Velu

+0

有很多用於綁定的polyfills,jQuery的'。.proxy'也可以用於這個用例。 – luwes