Migrating to Typeahead 0.10+ with Hogan

你离开我真会死。 提交于 2019-12-18 06:48:37

问题


I have been using Typeahead 0.9.3 with Hogan 2 for a while and it was very straight forward to setup.

in 0.9.3 I did something like:

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

According to the Migration Guide to 0.10 "Precompiled Templates are Now Required", so in 0.10.3 I'm trying:

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

but it does not work. I get an error: Uncaught TypeError: object is not a function

If there is another, minimalist template engine that can work I will consider it as well, but it has to be small. I don't want to add a huge file like Handlebars or a whole library like Underscore.

any ideas? TIA!


回答1:


As stated by Jake Harding, the solution for modern browsers is like so:

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

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

Unfortunately, Function.prototype.bind() is not supported by IE < 9, so if you need to support older browsers that will not work.

The good news is that as stated by Steve Pavarno you don't need a template engine anymore. You can achieve the desired result by passing a function like so:

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


来源:https://stackoverflow.com/questions/24727534/migrating-to-typeahead-0-10-with-hogan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!