Skip to content

Instantly share code, notes, and snippets.

@ericyd
Created September 14, 2018 17:19
Show Gist options
  • Save ericyd/fe4ce86a1143e86b821e0d12d5daf236 to your computer and use it in GitHub Desktop.
Save ericyd/fe4ce86a1143e86b821e0d12d5daf236 to your computer and use it in GitHub Desktop.
Fuse JS Web Worker implementation
/************************
search.js
************************/
// an example of how to implement fuse.js with a web worker
var searchWorker; // initialized in document ready function
if(typeof(Worker) !== "undefined") {
if(typeof(searchWorker) == "undefined") {
searchWorker = new Worker('/scripts/searchWorker.js');
}
searchWorker.addEventListener('message', function(e) {
var result = e.data.result;
var submitForm = e.data.submitForm;
var input = jQuery('#' + e.data.inputID);
setFaytResults(result, input, submitForm);
});
searchWorker.addEventListener('error', function(e) {
// if we want error handling, put it here
console.log(e);
});
} else {
// no web worker support - do we need/want a fallback?
}
function searchFuse(options, val, inputID, submitForm) {
var searchData = getSearchData();
searchWorker.postMessage({
searchData: searchData,
options: options,
val: val,
inputID: inputID,
submitForm: submitForm
});
}
/************************
searchWorker.js
************************/
/**
* Add event handler for "message" event.
* This is triggered whenever worker.postMessage() is called
* from the parent script.
*
* This function takes an event object with data bound to the `data` property.
* `input` and `submitForm` values are not used, but they are required in the
* message handler in the parent - thus, they are simply passed through.
*
* This function initializes a FuseJS object with the search options and then
* performs a search for the given value. The result array is returned in a message.
*/
// required to get access to the Fuse object
// self is the way to access the global scope within a web worker
self.importScripts('fuse/fuse.min.js');
onmessage = function receiver(e) {
var searchData = e.data.searchData;
var options = e.data.options;
var val = e.data.val;
var inputID = e.data.inputID;
var submitForm = e.data.submitForm;
try {
var fuse = new Fuse(searchData, options);
var result = fuse.search(val);
} catch (e) {
// assume this failed because FuseJS hadn't loaded yet. Load again and repeat
self.importScripts('fuse/dist/fuse.min.js');
var fuse = new Fuse(searchData, options);
var result = fuse.search(val);
}
// this will trigger the "message" event on the worker in the parent script.
// That is, the "onmessage" handler will be called whenever `postMessage()` is called.
postMessage({
result: result,
submitForm: submitForm,
inputID: inputID
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment