Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling functions in Web Workers

Ok this is kinda difficult to explain but here goes, I am using web workers and I have functions defined in my web workers script, and I would like to call a particular function passing in another function as arguments, the problem is I am trying to do this from my main script using worker.postMessage. It might be clearer if I post some code...

This is from my main script:

worker.postMessage({'cmd': 'register', 'funcName': 'someFunction'});

This is from the worker script:

self.addEventListener('message', function(e) {
    var data = e.data;

switch (data.cmd) {
    case 'register':
        registerEvent(data.funcName);
        break;
    case 'unregister':
        break;
    default:
        self.postMessage('Unknown command: ' + data.msg);
    };
}, false);

function someFunction() {

}

function registerEvent(someFunction) {

}

So I know this code is wrong and won't work, but I guess you have an idea of what I'm trying to achieve.

like image 287
Jack Avatar asked Aug 01 '13 16:08

Jack


2 Answers

I would do something like this:

self.addEventListener('message', function(e) {
    var data = e.data;

    switch (data.cmd) {
        case 'register':
            registerEvent(data.funcName);
            break;
        case 'unregister':
            break;
        default:
            self.postMessage('Unknown command: ' + data.msg);
    };
}, false);

self.someFunction = function() {}

function registerEvent(someFunctionName) {
    self[someFunctionName]();
}

or create a separate object with the function, but make sure it is a method of an object, then it becomes easy to call like that.

like image 158
kalley Avatar answered Sep 20 '22 23:09

kalley


I would recommend you to look at the vkTread plugin. This plugin allows you to execute any function of your code in a thread.

http://www.eslinstructor.net/vkthread/

Best regards,

--Vadim

like image 45
vadimk Avatar answered Sep 19 '22 23:09

vadimk