HTML and CSS Reference
In-Depth Information
it to tasks.appcache. This will ensure the Web Worker is stored on the client rather than
read from the server on demand when the Web Worker is created.
You will notice that when the Web Worker finishes it posts back an array of task objects to
a listener. Now we need to write the code that initializes the Web Worker, posts a message
to it, and listens for a message in response. This is the code that will execute on the main
browser thread.
In order to instantiate a Web Worker we use the following code:
var worker = new Worker('scripts/tasks-csvparser.js');
Note that this contains the URL of the JavaScript file that will constitute the Web Worker.
Once the Web Worker is created we need to add an event listener to it so that we can hear
when it posts messages back to the main browser thread. In our case, this event listener will
receive an array of tasks, which it will then save:
worker.addEventListener('message', function(e) {
var tasks = e.data;
storageEngine.saveAll('task', tasks, function() {
tasksController.loadTasks();
},errorLogger);
}, false);
Finally we need to post a message to the Web Worker:
worker.postMessage(contents);
If we put all of that together, the loadFromCSV function should now look like this:
function loadFromCSV(event) {
var reader = new FileReader();
reader.onload = function(evt) {
var contents = evt.target.result;
var worker = new Worker('scripts/tasks-csvparser.js');
worker.addEventListener('message', function(e) {
var tasks = e.data;
storageEngine.saveAll('task', tasks, function() {
tasksController.loadTasks();
},errorLogger);
}, false);
worker.postMessage(contents);
Search WWH ::




Custom Search