I'm new to typeahead.js, I'm doing an auto complete here. Problem is what should be the source here, what does it return and what is the function of handlebar here.
<div id="custom-templates">
<input class="typeahead" type="text" placeholder="Oscar winners for Best Picture"/>
</div>
$('#custom-templates .typeahead').typeahead(null, {
name: 'best-pictures',
displayKey: 'value',
source: bestPictures.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'unable to find any Best Picture winners that match the current query',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<p><strong>{{value}}</strong> – {{year}}</p>')
}
});
I just took this example to study from twitter, but what is the source and how it is delivered to handlebar? If the source is a jsondata how it can be rendered?
source
is a function that is called when the pattern changes (i.e. as the user edits the text field) and which should return an array of matches.
Here is an example of a source which matches substrings in an array of strings:
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
// the typeahead jQuery plugin expects suggestions to a
// JavaScript object, refer to typeahead docs for more info
matches.push({ value: str });
}
});
cb(matches);
};
};
To use this:
source: substringMatcher(['Alabama', 'Alaska', 'Arizona', 'Arkansas'])
Related: