Question

I am trying to load autocompletion information of people's names for typeahead and then not have to query the server again if I already have a result.

For example if i search a person's name and the data for that person (among others) gets retrieved from a remote query, when I delete the name and search for the surname instead I want to have the previously cached names with that surname to show up. What actually happens is that the results are again retrieved from the server and the suggested.

Caching only works while typing a single word ("Mic" -> "Mich" -> "Micha" -> "Michael").

TL;DR: I want to cache results from bloodhound in Local Storage not only from prefetch (which cannot be applied to my situation) but from remote as well and use that before querying remote again.

What i currently have is

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(),
});

I haven't found something similar and i am afraid there is no trivial solution to this.

P.S.: I also noticed that datumTokenizer never gets called

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

when i used this, "Lalalalala" was never outputted in the chrome debug console.

Was it helpful?

Solution

As jharding mentioned it's not possible to have remote suggestions pulled from localstorage at this point.

However, I recently worked on a small project where I needed to store previous form inputs for future use in typeahead.js. To do this I saved an array of form input values to localstorage.

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

I then retrieved the array for use in the typeahead field.

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

You can view my full source here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top