diff --git a/core/workspace.js b/core/workspace.js index ac62f3fd2..400412a31 100644 --- a/core/workspace.js +++ b/core/workspace.js @@ -36,6 +36,9 @@ goog.require('goog.math'); * @constructor */ Blockly.Workspace = function(opt_options) { + /** @type {string} */ + this.id = Blockly.genUid(); + Blockly.Workspace.WorkspaceDB_[this.id] = this; /** @type {!Object} */ this.options = opt_options || {}; /** @type {boolean} */ @@ -56,6 +59,8 @@ Blockly.Workspace.prototype.rendered = false; */ Blockly.Workspace.prototype.dispose = function() { this.clear(); + // Remove from workspace database. + delete Blockly.Workspace.WorkspaceDB_[this.id]; }; /** @@ -195,5 +200,20 @@ Blockly.Workspace.prototype.fireChangeEvent = function() { // NOP. }; +/** + * Database of all workspaces. + * @private + */ +Blockly.Workspace.WorkspaceDB_ = Object.create(null); + +/** + * Find the workspace with the specified ID. + * @param {string} id ID of workspace to find. + * @return {Blockly.Workspace} The sought after workspace or null if not found. + */ +Blockly.Workspace.getById = function(id) { + return Blockly.Workspace.WorkspaceDB_[id] || null; +}; + // Export symbols that would otherwise be renamed by Closure compiler. Blockly.Workspace.prototype['clear'] = Blockly.Workspace.prototype.clear; diff --git a/tests/jsunit/block_test.js b/tests/jsunit/block_test.js index a799340bc..de4f36ffd 100644 --- a/tests/jsunit/block_test.js +++ b/tests/jsunit/block_test.js @@ -19,7 +19,7 @@ */ 'use strict'; -function test_getById() { +function test_getBlockById() { var workspace = new Blockly.Workspace(); var blockA = workspace.newBlock(''); var blockB = workspace.newBlock(''); diff --git a/tests/jsunit/workspace_test.js b/tests/jsunit/workspace_test.js index cf18f162e..2033b9ae0 100644 --- a/tests/jsunit/workspace_test.js +++ b/tests/jsunit/workspace_test.js @@ -66,3 +66,19 @@ function test_maxBlocksWorkspace() { workspace.clear(); assertEquals('Cleared capacity.', 0, workspace.remainingCapacity()); } + +function test_getWorkspaceById() { + var workspaceA = new Blockly.Workspace(); + var workspaceB = new Blockly.Workspace(); + assertEquals('Find workspaceA.', workspaceA, + Blockly.Workspace.getById(workspaceA.id)); + assertEquals('Find workspaceB.', workspaceB, + Blockly.Workspace.getById(workspaceB.id)); + assertEquals('No workspace found.', null, + Blockly.Workspace.getById('I do not exist.')); + workspaceA.dispose(); + assertEquals('Can\'t find workspaceA.', null, + Blockly.Workspace.getById(workspaceA.id)); + assertEquals('WorkspaceB exists.', workspaceB, + Blockly.Workspace.getById(workspaceB.id)); +}