mirror of
https://github.com/scratchfoundation/scratch-vm.git
synced 2024-12-22 22:12:28 -05:00
Update index.js to support worker environment
This commit is contained in:
parent
01aecb3372
commit
783a3688aa
1 changed files with 55 additions and 0 deletions
55
src/index.js
55
src/index.js
|
@ -4,6 +4,12 @@ var util = require('util');
|
|||
var Blocks = require('./engine/blocks');
|
||||
var Runtime = require('./engine/runtime');
|
||||
|
||||
/**
|
||||
* Whether the environment is a WebWorker.
|
||||
* @const{boolean}
|
||||
*/
|
||||
var ENV_WORKER = typeof importScripts === 'function';
|
||||
|
||||
/**
|
||||
* Handles connections between blocks, stage, and extensions.
|
||||
*
|
||||
|
@ -30,6 +36,55 @@ function VirtualMachine () {
|
|||
);
|
||||
}
|
||||
|
||||
/*
|
||||
* Worker Handlers
|
||||
*/
|
||||
if (ENV_WORKER) {
|
||||
self.vmInstance = new VirtualMachine();
|
||||
self.onmessage = function (e) {
|
||||
var messageData = e.data;
|
||||
switch (messageData.method) {
|
||||
case 'start':
|
||||
self.vmInstance.runtime.start();
|
||||
break;
|
||||
case 'greenFlag':
|
||||
self.vmInstance.runtime.greenFlag();
|
||||
break;
|
||||
case 'stopAll':
|
||||
self.vmInstance.runtime.stopAll();
|
||||
break;
|
||||
case 'blockListener':
|
||||
self.vmInstance.blockListener(messageData.args);
|
||||
break;
|
||||
case 'flyoutBlockListener':
|
||||
self.vmInstance.flyoutBlockListener(messageData.args);
|
||||
break;
|
||||
case 'getPlaygroundData':
|
||||
self.postMessage({
|
||||
method: 'playgroundData',
|
||||
blocks: self.vmInstance.blocks,
|
||||
threads: self.vmInstance.runtime.threads
|
||||
});
|
||||
break;
|
||||
default:
|
||||
throw 'Unknown method' + messageData.method;
|
||||
}
|
||||
};
|
||||
// Bind runtime's emitted events to postmessages.
|
||||
self.vmInstance.runtime.on(Runtime.STACK_GLOW_ON, function (id) {
|
||||
self.postMessage({method: Runtime.STACK_GLOW_ON, id: id});
|
||||
});
|
||||
self.vmInstance.runtime.on(Runtime.STACK_GLOW_OFF, function (id) {
|
||||
self.postMessage({method: Runtime.STACK_GLOW_OFF, id: id});
|
||||
});
|
||||
self.vmInstance.runtime.on(Runtime.BLOCK_GLOW_ON, function (id) {
|
||||
self.postMessage({method: Runtime.BLOCK_GLOW_ON, id: id});
|
||||
});
|
||||
self.vmInstance.runtime.on(Runtime.BLOCK_GLOW_OFF, function (id) {
|
||||
self.postMessage({method: Runtime.BLOCK_GLOW_OFF, id: id});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from EventEmitter
|
||||
*/
|
||||
|
|
Loading…
Reference in a new issue