【问题标题】:Switch between remote and local sources with Typeahead.js/Bloodhound.js使用 Typeahead.js/Bloodhound.js 在远程和本地源之间切换
【发布时间】:2016-03-30 02:56:20
【问题描述】:

我尝试了所有我能想到的设置,例如.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>';
        }
    }
});

};

【问题讨论】:

  • 我看错了你的问题。从远程切换到本地,而不是远程源。如果有任何理由你不只是使用远程或本地?任何一个都可以处理返回数据的函数。
  • 我有多个要在多个预输入之间切换。
  • 你能扩展一下吗?你需要使用猎犬吗?如果您可以简单地将预先输入的源定义为一个函数,那么您可以通过该函数处理获取任何数据(本地 json、ajax 调用等)。
  • 谢谢,我可能会摆脱猎犬。我知道它被称为建议引擎,但通过谷歌搜索,我无法理解它的作用,除了惹恼每个人的废话。我希望同一个输入框来处理不同的数据源,一些是本地的,一些是远程的,具体取决于用户的预过滤。
  • 即使您保留 Bloodhound(它比预输入更可靠地清除和初始化),您也可以使用 local 使用将数据返回到本地的函数。如果你用遥控器,那就不一样了。您可以更改 url 和参数,但您始终必须从 url 获取数据。

标签: javascript jquery autocomplete typeahead.js bloodhound


【解决方案1】:

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

当您想使用 bloodhound 更改 remote 源时,您必须清除寻血猎犬对象并重新初始化它。

这里我正在创建一个初始化寻血犬实例:

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 显示我如何处理它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2014-10-08
    • 2020-12-22
    • 2015-01-19
    相关资源
    最近更新 更多