Caching Autocomplete Responses Using Lodash
How to cache the term responses of jQuery UI autocompletes using Lodash functions.
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags" />
</div>
CSS
body {
margin: 3em;
font-size: 0.8em;
}
JavaScript
(function( $ ) {
$.widget( 'app.autocomplete', $.ui.autocomplete, {
terms: {},
_initSource: function() {
this._super();
this.source = _.wrap( this.source, this.cache );
},
cache: function( source, req, res ) {
_.has( this.terms, req.term ) ?
res( this.terms[ req.term ] ) :
source( req, res );
},
__response: function( content ) {
if ( !_.has( this.terms, this.term ) ) {
this.terms[ this.term ] = 'a';
}
this._super( content );
}
});
$( function() {
$( '#tags' ).autocomplete({
source: [
'ActionScript', 'AppleScript',
'Asp', 'BASIC', 'C', 'C++',
'Clojure', 'COBOL',
'ColdFusion', 'Erlang',
'Fortran', 'Groovy',
'Haskell', 'Java',
'JavaScript', 'Lisp',
'Perl', 'PHP', 'Python',
'Ruby', 'Scala', 'Scheme'
]
});
});
})( jQuery );