抱歉,如果这是一个有明显答案的问题,但我是 Java、Spring/Hibernate、jQuery 等堆栈的新手。使用 Firebug,我能够弄清楚 typeahead 和 Bloodhound 都需要什么,并得出以下结论:
//token and filter functions
function ingredDatumToken(datum) {
return Bloodhound.tokenizers.whitespace(datum.name);
}
function ingredPrefetchFilter(data) {
return $.map(data.ingredients, function (ingredient) {
return {
id : ingredient.id,
name : ingredient.name
};
});
};
function ingredRemoteFilter(data) {
return $.map(data, function (data) {
return {
id : data.id,
name : data.name
};
});
};
//Bloodhound initialization
function initBloodhound(limit, cache, datumToken, queryToken,prefetchUrl,prefetchFilter, remoteUrl, wildcard, remoteFilter)
{
var token = Bloodhound.tokenizers.whitespace;
var options = {};
var prefetchOptions = {};
var remoteOptions = {};
prefetchOptions['url'] = prefetchUrl;
prefetchOptions['cache'] = cache;
prefetchOptions['filter'] = prefetchFilter;
remoteOptions['url'] = remoteUrl;
remoteOptions['cache'] = cache;
remoteOptions['wildcard'] = wildcard;
remoteOptions['filter'] = remoteFilter;
options['limit'] = limit;
options['datumTokenizer'] = datumToken === null ? token : datumToken;
options['queryTokenizer'] = queryToken === null ? token : queryToken;
if (prefetchUrl != null)
options['prefetch'] = prefetchOptions;
if (remoteUrl != null)
options['remote'] = remoteOptions;
return new Bloodhound(options);
};
//create two Bloodhound engines
var ingredBH = initBloodhound(50,false,ingredDatumToken,null,'/myapp/resources/ingredients.json',ingredPrefetchFilter,'/myapp/recipeaddRecipe/getIngredients?searchStr=%QUERY','%QUERY',ingredRemoteFilter);
var measureBH = initBloodhound(20,false,null,null,'/myapp/resources/measures.json',null,null,null,null);
//add more Bloodhound engines here
//typeahead options
function initTypeaheadOptions(hint, highlight, minLength) {
var options = {};
options['hint'] = hint;
options['highlight'] = highlight;
options['minLength'] = minLength;
return options;
}
//typeahead dataset
function initTypeaheadDataset(name, displayKey, limit, source) {
var datasets = {};
datasets['name'] = name;
datasets['displayKey'] = displayKey;
datasets['limit'] = limit;
datasets['source'] = source;
return datasets;
}
//initialize a typeahead control
function initIngredientsTA() {
var options = initTypeaheadOptions(true,true,1);
var dataset = initTypeaheadDataset('ingredients', 'name', 20, ingredBH);
$('.ingredDesc').typeahead(options,dataset);
};
//initialize a typeahead control
function initMeasuresTA() {
var options = initTypeaheadOptions(true,true,1);
var dataset = initTypeaheadDataset('measures', null, 20, measureBH);
$('.ingredQtyType').typeahead(options,datasets);
};
//add more typeahead initialization functions here
//call the initialize functions
initIngredientsTA();
initMeasuresTA();
//call more initialize functions here
我仍在努力使其更加通用,并且我并不热衷于调用 Bloodhound 初始化函数中的所有参数,但由于我将在页面上拥有大约 10 个或更多启用预输入的控件,因此这将是相当不错的。只需几行代码即可轻松添加其余部分。那些不属于页面上动态创建的行的预输入控件不需要单独的初始化函数,但只需 3 行代码即可初始化。我绝对愿意接受任何改进意见或建议,包括任何认为这是一个愚蠢想法的想法。