4

我已经在 Hogan 2 上使用 Typeahead 0.9.3 有一段时间了,它的设置非常简单。

在 0.9.3 我做了类似的事情:

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

根据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 这样的整个库。

有任何想法吗?蒂亚!

4

1 回答 1

9

正如 Jake Harding 所说,现代浏览器的解决方案是这样的:

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

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

不幸的是,IE < 9 不支持 Function.prototype.bind(),因此如果您需要支持将无法工作的旧浏览器。

好消息是,正如 Steve Pavarno 所说,您不再需要模板引擎。您可以通过传递如下函数来实现所需的结果:

    // ...
    templates: {
        suggestion: function(data) { // data is an object as returned by suggestion engine
            return '<div class="tt-suggest-page">' + data.value + '</div>';
        };
    }
于 2014-07-13T23:36:12.717 回答