繁体   English   中英

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

[英]Switch between remote and local sources with Typeahead.js/Bloodhound.js

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

有什么想法吗?

这是下面的代码,称为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更改remote源时,您将必须清除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;
},

这是一个完整的示例,展示了我如何处理它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM