【问题标题】:Migrating to Typeahead 0.10+ with Hogan使用 Hogan 迁移到 Typeahead 0.10+
【发布时间】:2014-07-13 22:38:35
【问题描述】:

我已经在 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
    }
]);

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

有什么想法吗?蒂亚!

【问题讨论】:

    标签: javascript template-engine typeahead.js hogan.js twitter-typeahead


    【解决方案1】:

    正如 Jake Harding 所说,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>';
            };
        }
    

    【讨论】:

    • 请注意,如果您的数据可以包含 HTML 特殊字符(例如 "'&),则上面列出的非模板引擎版本是不安全的,您需要对其进行转义。
    • 有许多用于绑定的 polyfill,jQuery 的$.proxy 也适用于这个用例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 2013-10-17
    • 2011-11-26
    • 2018-11-08
    • 2019-09-04
    • 1970-01-01
    相关资源
    最近更新 更多