Search code examples
javascripttypeahead.jshogan.js

How to reset a Hogan.js template used in typeahead.js


Im new to both Hogan.js and typeahead.js so this question is probably silly.

$('.example-twitter-oss .typeahead').typeahead({                              
      name: 'twitter-oss',                                                        
      prefetch: 'repos.json',                                             
      template: [                                                                 
        '<p class="type">{{language}}</p>',                              
        '<p class="name">{{name}}</p>',                                      
        '<p class="description">{{description}}</p>'
      ].join(''),
      engine: Hogan
});

This is how I created my instance of typeahead.js with Hogan.js as template. Now that I want to change my test-data: 'repos.json', the template is still the same. I guess its cached somehow. How can I reset my template to contain new data?

I see hogan have a compile(); and render() method, but I dont understand how to use it.

I use the newest version of both.


Solution

  • In the current version of typeahead.js (0.9.3), datasets are cached by their name property and there's no way to bust the cache. So if you have:

    $('.example-twitter-oss .typeahead').typeahead({
      name: 'twitter-oss',                                                        
      prefetch: 'repos.json',                                             
      template: [                                                                 
        '<p class="type">{{language}}</p>',                              
        '<p class="name">{{name}}</p>',                                      
        '<p class="description">{{description}}</p>'
      engine: Hogan
    });
    
    $('.example-something-different .typeahead').typeahead({
      name: 'twitter-oss',
      prefetch: 'something_different.json'
    });
    

    .example-something-different .typeahead wouldn't use the configuration specified, it'd use the configuration specified by .example-twitter-oss .typeahead because they use the same name. This isn't intuitive and it's something that will be changing in the next release, v0.10. For now though, you can circumvent this problem by using different names:

    $('.example-twitter-oss .typeahead').typeahead({
      name: 'twitter-oss',
      prefetch: 'repos.json',
      template: [
        '<p class="type">{{language}}</p>',
        '<p class="name">{{name}}</p>', 
        '<p class="description">{{description}}</p>'
      ].join(''),
      engine: Hogan
    });
    
    $('.example-something-different .typeahead').typeahead({
      name: 'something different',
      prefetch: 'something_different.json'
    });