Interacting with Wasm in WasmWorker.js

Create a new file in the /src directory named WasmWorker.js and populate it with the following contents:

/**
* Web Worker associated with an instantiated Wasm module.
* @class
*/
export default class WasmWorker {
constructor(workerUrl) {
this.worker = new Worker(workerUrl);
this.listenersByType = {};
this.addListeners();
}

// Add a listener associated with the `type` value from the
// Worker message:
addListenerForType(type, listener) {
this.listenersByType[type] = listener;
}

// Add event listeners for error and message handling.
addListeners() {
this.worker.addEventListener('error', event => {
console.error(`%cError: ${event.message}`, 'color: red;');
}, false);

// If a handler was specified using the `addListener` method,
// fire that method if the `type` matches:
this.worker.addEventListener('message', event => {
if (
event.data instanceof Object &&
event.data.hasOwnProperty('type') &&
event.data.hasOwnProperty('payload')
) {
const { type, payload } = event.data;
if (this.listenersByType[type]) {
this.listenersByType[type](payload);
}
} else {
console.log(event.data);
}
}, false);
}

// Fetches the Wasm file, compiles it, and passes the compiled result
// to the corresponding worker. The compiled module is instantiated
// in the worker.
initialize(name) {
return fetch(`calc-${name}.wasm`)
.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.compile(bytes))
.then(wasmModule => {
this.worker.postMessage({
type: 'COMPILE_WASM_REQUEST',
payload: wasmModule
});
return Promise.resolve();
});
}

// Posts a message to the worker thread to call the `calculate`
// method from the Wasm instance:
calculate(firstVal, secondVal) {
this.worker.postMessage({
type: 'CALC_REQUEST',
payload: {
firstVal,
secondVal
}
});
}
}

The WasmWorker class manages a worker thread associated with a Wasm file. In the WasmWorker constructor, a new Worker is created and default event listeners are added for the error and message events. The initialize() function fetches the .wasm file associated with the name argument, compiles it, and sends the resultant WebAssembly.Module instance to the worker thread to be instantiated.

The addListenerForType() function is used to specify a callback function (listener) to execute when the type field in the message response matches the type argument passed to the function. This is required to capture the result of the _calculate() function from the worker thread.

Finally, the calculate() function in WasmWorker posts a message to the worker thread with the firstVal and secondVal arguments passed in from the <input> elements on the <form>. Let's move on to the application loading code to see how WasmWorker interacts with the UI.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset