Bloodhound不会缓存本地存储中远程提取的数据

时间:2014-03-03 10:09:16

标签: caching local-storage typeahead.js bloodhound

我正在尝试为typeahead加载人名的自动完成信息,如果我已经有结果,则不必再次查询服务器。

例如,如果我搜索一个人的名字,并且从远程查询中检索该人(以及其他人)的数据,当我删除该名称并搜索姓氏时,我希望拥有该姓氏的先前缓存名称现身。实际发生的是,再次从服务器和建议中检索结果。

缓存仅在键入单个单词时有效(“Mic” - >“Mich” - >“Micha” - >“Michael”)。

TL; DR:我想在本地存储中缓存来自本地存储中的猎犬的结果,不仅来自预取(不能应用于我的情况),也来自远程也是如此,并在再次查询远程之前使用它。

我目前拥有的是

function dispkey(suggestion_object){
  console.log(suggestion_object);
  return suggestion_object["lastname"] + ", " + suggestion_object["firstname"];
}

var engine = new Bloodhound({
  name: 'authors',
  local: [],
  remote: 'http://xxxxxx.xxx/xxxx/xxxxxxxxxx?query=%%QUERY',
  datumTokenizer: function(d) {
    return Bloodhound.tokenizers.whitespace(d.val);
  },
  queryTokenizer: function (s){
    return s.split(/[ ,]+/);
  },
});

engine.initialize();

$('.typeahead').typeahead({
    highlight: true,
    hint: true,
    minLength: 3,
},
{
  displayKey: dispkey,
  templates: {
     suggestion: Handlebars.compile([
      '<p id="author_autocomplete_email_field" >{{email}}</p>',
      '<p id="author_autocomplete_name_field">{{lastname}} {{firstname}}</p>',
      ].join(''))},
  source: engine.ttAdapter(),
});

我没有发现类似的东西,我担心没有这方面的解决方案。

P.S。:我也注意到datumTokenizer永远不会被调用

datumTokenizer: function(d) {
    console.log("Lalalalala");
    return Bloodhound.tokenizers.whitespace(d.val);
  },

当我使用它时,“Lalalalala”从未在chrome调试控制台中输出。

1 个答案:

答案 0 :(得分:3)

正如jharding所述,此时无法从localstorage提取远程建议。

但是,我最近在一个小项目上工作,我需要存储以前的表单输入以供将来在typeahead.js中使用。为此,我将表单输入值数组保存到localstorage

var inputs = ['val1', 'val2', 'val3', 'val4'];
localStorage.setItem('values', JSON.stringify(inputs));

然后我检索了数组以便在typeahead字段中使用。

var data = JSON.parse(localStorage.getItem('values'));
$('input').typeahead({
    minLength: 3,
    highlight: true,
},
{
    name: 'data',
    displayKey: 'value',
    source: this.substringMatcher(data)
});

您可以查看我的full source here