gpt4 book ai didi

javascript - 使用 Typeahead.js/Bloodhound.js 在远程和本地源之间切换

转载 作者:行者123 更新时间:2023-12-03 07:18:36 25 4
gpt4 key购买 nike

我尝试过所有我能想到的设置,例如 .clear().typeahead('destroy'),一旦我将源设置为远程我无法使预输入使用本地源。

有什么想法吗?

下面是调用 onclick 的代码:

var create_typeahead = function(is_remote, titles){

filters_typeahead.typeahead('destroy');

if(is_remote){
var remote_url = titles;
var titles = new Bloodhound({
queryTokenizer: Bloodhound.tokenizers.whitespace,
datumTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: remote_url,
q=%QUERY',
wildcard: '%QUERY'
}
});
}
else{
var titles0 = titles;
var titles = new Bloodhound({
queryTokenizer: Bloodhound.tokenizers.whitespace,
datumTokenizer: Bloodhound.tokenizers.whitespace,
local: titles0
});
}

titles.initialize();

filters_typeahead.typeahead({
highlight: true,
minLength: 2,

},
{
name: 'titles',
displayKey: 'name',
source: titles,
templates: {
suggestion: function(data) {
return '<div>' + data.name + '</div>';
}
}
});

};

最佳答案

我的回答比你的更复杂一些,但希望它能为你指明正确的方向。

当您想要使用bloodhound更改远程源时,您必须清除bloodhound对象并重新初始化它。

这里我正在创建一个初始化 Bloodhound 实例:

var taSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) {
return obj.Value;
},
remote: remoteSrc
});

taSource.initialize(true);

在切换逻辑中,我调用 clear()initialize(true),为重新初始化参数传递 true:

taSource.clear();
taSource.initialize(true);

我在 prepare 方法中处理 URL 的更改,该方法作为 remote 对象的一部分提供。

prepare: function(query, settings) {
settings.url = urlRoot + '/' + whichType + '?q=' + query;
console.log(settings.url);
return settings;
},

Here is a full example展示我如何处理它。

关于javascript - 使用 Typeahead.js/Bloodhound.js 在远程和本地源之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36298830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com