Blame | Last modification | View Log | RSS feed
Bloodhound==========Bloodhound is the typeahead.js suggestion engine. Bloodhound is robust,flexible, and offers advanced functionalities such as prefetching, intelligentcaching, fast lookups, and backfilling with remote data.Table of Contents-----------------* [Features](#features)* [Usage](#usage)* [API](#api)* [Options](#options)* [Prefetch](#prefetch)* [Remote](#remote)* [Datums](#datums)* [Tokens](#tokens)Features--------* Works with hardcoded data* Prefetches data on initialization to reduce suggestion latency* Uses local storage intelligently to cut down on network requests* Backfills suggestions from a remote source* Rate-limits and caches network requests to remote sources to lighten the loadUsage-----### API#### new Bloodhound(options)The constructor function. It takes an [options hash](#options) as its onlyargument.```javascriptvar engine = new Bloodhound({name: 'animals',local: [{ val: 'dog' }, { val: 'pig' }, { val: 'moose' }],remote: 'http://example.com/animals?q=%QUERY',datumTokenizer: function(d) {return Bloodhound.tokenizers.whitespace(d.val);},queryTokenizer: Bloodhound.tokenizers.whitespace});```#### Bloodhound#initialize(reinitialize)Kicks off the initialization of the suggestion engine. This includes processingthe data provided through `local` and fetching/processing the data providedthrough `prefetch`. Until initialized, all other methods will behave as no-ops.Returns a [jQuery promise] which is resolved when engine has been initialized.```javascriptvar promise = engine.initialize();promise.done(function() { console.log('success!'); }).fail(function() { console.log('err!'); });```After the initial call of `initialize`, how subsequent invocations of the methodbehave depends on the `reinitialize` argument. If `reinitialize` is falsy, themethod will not execute the initialization logic and will just return the samejQuery promise returned by the initial invocation. If `reinitialize` is truthy,the method will behave as if it were being called for the first time.```javascriptvar promise1 = engine.initialize();var promise2 = engine.initialize();var promise3 = engine.initialize(true);promise1 === promise2;promise3 !== promise1 && promise3 !== promise2;```#### Bloodhound#add(datums)Takes one argument, `datums`, which is expected to be an array of[datums](#datums). The passed in datums will get added to the search index thatpowers the suggestion engine.```javascriptengine.add([{ val: 'one' }, { val: 'two' }]);```#### Bloodhound#clear()Removes all suggestions from the search index.```javascriptengine.clear();```#### Bloodhound#clearPrefetchCache()If you're using `prefetch`, data gets cached in local storage in an effort tocut down on unnecessary network requests. `clearPrefetchCache` offers a way toprogrammatically clear said cache.```javascriptengine.clearPrefetchCache();```#### Bloodhound#clearRemoteCache()If you're using `remote`, Bloodhound will cache the 10 most recent responsesin an effort to provide a better user experience. `clearRemoteCache` offers away to programmatically clear said cache.```javascriptengine.clearRemoteCache();```#### Bloodhound.noConflict()Returns a reference to the Bloodhound constructor and reverts`window.Bloodhound` to its previous value. Can be used to avoid namingcollisions.```javascriptvar Dachshund = Bloodhound.noConflict();```<!-- section links -->[jQuery promise]: http://api.jquery.com/Types/#Promise#### Bloodhound#get(query, cb)Computes a set of suggestions for `query`. `cb` will be invoked with an arrayof datums that represent said set. `cb` will always be invoked oncesynchronously with suggestions that were available on the client. If thosesuggestions are insufficient (# of suggestions is less than `limit`) and `remote` was configured, `cb` may also beinvoked asynchronously with the suggestions available on the client mixed withsuggestions from the `remote` source.```javascriptbloodhound.get(myQuery, function(suggestions) {suggestions.each(function(suggestion) { console.log(suggestion); });});```### OptionsWhen instantiating a Bloodhound suggestion engine, there are a number ofoptions you can configure.* `datumTokenizer` – A function with the signature `(datum)` that transforms adatum into an array of string tokens. **Required**.* `queryTokenizer` – A function with the signature `(query)` that transforms aquery into an array of string tokens. **Required**.* `limit` – The max number of suggestions to return from `Bloodhound#get`. Ifnot reached, the data source will attempt to backfill the suggestions from`remote`. Defaults to `5`.* `dupDetector` – If set, this is expected to be a function with the signature`(remoteMatch, localMatch)` that returns `true` if the datums are duplicates or`false` otherwise. If not set, duplicate detection will not be performed.* `sorter` – A [compare function] used to sort matched datums for a given query.* `local` – An array of [datums](#datums) or a function that returns an array ofdatums.* `prefetch` – Can be a URL to a JSON file containing an array of datums or, ifmore configurability is needed, a [prefetch options hash](#prefetch).* `remote` – Can be a URL to fetch suggestions from when the data provided by`local` and `prefetch` is insufficient or, if more configurability is needed,a [remote options hash](#remote).<!-- section links -->[compare function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort### PrefetchPrefetched data is fetched and processed on initialization. If the browsersupports local storage, the processed data will be cached there toprevent additional network requests on subsequent page loads.**WARNING:** While it's possible to get away with it for smaller data sets,prefetched data isn't meant to contain entire data sets. Rather, it should actas a first-level cache for suggestions. If don't keep this warning in mind,you run the risk of hitting [local storage limits].When configuring `prefetch`, the following options are available.* `url` – A URL to a JSON file containing an array of datums. **Required.*** `cacheKey` – The key that data will be stored in local storage under.Defaults to value of `url`.* `ttl` – The time (in milliseconds) the prefetched data should be cached inlocal storage. Defaults to `86400000` (1 day).* `thumbprint` – A string used for thumbprinting prefetched data. If thisdoesn't match what's stored in local storage, the data will be refetched.* `filter` – A function with the signature `filter(parsedResponse)` thattransforms the response body into an array of datums. Expected to return anarray of datums.* `ajax` – The [ajax settings object] passed to `jQuery.ajax`.<!-- section links -->[local storage limits]: http://stackoverflow.com/a/2989317[ajax settings object]:http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings### RemoteRemote data is only used when the data provided by `local` and `prefetch` isinsufficient. In order to prevent an obscene number of requests being made tothe remote endpoint, requests are rate-limited.When configuring `remote`, the following options are available.* `url` – A URL to make requests to when when the data provided by `local` and`prefetch` is insufficient. **Required.*** `wildcard` - The pattern in `url` that will be replaced with the user's querywhen a request is made. Defaults to `%QUERY`.* `replace` – A function with the signature `replace(url, query)` that can beused to override the request URL. Expected to return a valid URL. If set, nowildcard substitution will be performed on `url`.* `rateLimitBy` – The method used to rate-limit network requests. Can be either`debounce` or `throttle`. Defaults to `debounce`.* `rateLimitWait` – The time interval in milliseconds that will be used by`rateLimitBy`. Defaults to `300`.* `filter` – A function with the signature `filter(parsedResponse)` thattransforms the response body into an array of datums. Expected to return anarray of datums.* `ajax` – The [ajax settings object] passed to `jQuery.ajax`.<!-- section links -->[ajax settings object]: http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings### DatumsDatums are JavaScript objects that hydrate the pool of possible suggestions.Bloodhound doesn't expect datums to contain any specific properties as anyoperations performed on datums are done using functions defined by the user i.e.`datumTokenizer`, `dupDetector`, and `sorter`.### TokensThe algorithm used by bloodhounds for providing suggestions for a given queryis token-based. When `Bloodhound#get` is called, it tokenizes `query` using`queryTokenizer` and then invokes `cb` with all of the datums that contain thosetokens.For a quick example, if a datum was tokenized into the following set oftokens...```javascript['typeahead.js', 'typeahead', 'autocomplete', 'javascript'];```...it would be a valid match for queries such as:* `typehead`* `typehead.js`* `autoco`* `java type`