Blockly.common.defineBlocksWithJsonArray([{"type":"string_length","message0":'lengthof%1',"args0":[{"type":"input_value","name":"VALUE","check":"String"}],"output":"Number","colour":160,"tooltip":"Returns number of letters in the provided text.","helpUrl":"http://www.w3schools.com/jsref/jsref_length_string.asp"}]);
Blockly.Blocks['string_length']={init:function(){this.appendValueInput('VALUE').setCheck('String').appendField('length of');this.setOutput(true,'Number');this.setColour(160);this.setTooltip('Returns number of letters in the provided text.');this.setHelpUrl('http://www.w3schools.com/jsref/jsref_length_string.asp');}};
以下示例使用 init 函数创建了块定义,该函数使用 jsonInit 加载 JSON 对象,并使用 JavaScript API 定义动态提示。
JavaScript
// Define the block structure in JSON.varmathChangeJson={"message0":"change %1 by %2","args0":[{"type":"field_variable","name":"VAR","variable":"item","variableTypes":[""]},{"type":"input_value","name":"DELTA","check":"Number"}],"previousStatement":null,"nextStatement":null,"colour":230};Blockly.Blocks['math_change']={init:function(){// Use jsonInit to load the JSON block structure.this.jsonInit(mathChangeJson);// Use JavaScript to define a tooltip function.// Assign 'this' to a variable for use in the tooltip closure below.varthisBlock=this;this.setTooltip(function(){return'Add a number to variable "%1".'.replace('%1',thisBlock.getFieldValue('VAR'));});}};
[null,null,["最后更新时间 (UTC):2025-07-25。"],[],[],null,["# JSON and JavaScript\n\nBlockly has two ways of defining blocks: JSON objects, which use key-value\npairs, and JavaScript functions, which call Blockly's API. The JSON format is\npreferred because it [simplifies\nlocalization](/blockly/guides/configure/web/translations#json_message_interpolation)\nand is easier to read and write. However, it cannot be used to directly define\nadvanced features such as mutators or validators. These must be written in\nJavaScript, usually as\n[extensions](/blockly/guides/create-custom-blocks/define/extensions).\n| **Key Term:** The \"JSON\" objects are, in fact, plain JavaScript objects. They are called JSON objects because their values must be serializable as JSON. The term is used because (a) it appears in the Blockly API and (b) it is a convenient way to distinguish between the two different methods of defining blocks.\n\nUse JSON or JavaScript\n----------------------\n\nThis block:\n\ncan be defined in JSON or JavaScript as follows. \n\n### JSON\n\n Blockly.common.defineBlocksWithJsonArray([{\n \"type\": \"string_length\",\n \"message0\": 'length of %1',\n \"args0\": [\n {\n \"type\": \"input_value\",\n \"name\": \"VALUE\",\n \"check\": \"String\"\n }\n ],\n \"output\": \"Number\",\n \"colour\": 160,\n \"tooltip\": \"Returns number of letters in the provided text.\",\n \"helpUrl\": \"http://www.w3schools.com/jsref/jsref_length_string.asp\"\n }]);\n\n`defineBlocksWithJsonArray` converts each JSON object into a [block\ndefinition object](/blockly/guides/create-custom-blocks/define/block-definitions)\nwith an `init` function. It stores these objects in `Blockly.Blocks`.\n\n### JavaScript\n\n Blockly.Blocks['string_length'] = {\n init: function() {\n this.appendValueInput('VALUE')\n .setCheck('String')\n .appendField('length of');\n this.setOutput(true, 'Number');\n this.setColour(160);\n this.setTooltip('Returns number of letters in the provided text.');\n this.setHelpUrl('http://www.w3schools.com/jsref/jsref_length_string.asp');\n }\n };\n\nBecause [block definition\nobjects](/blockly/guides/create-custom-blocks/define/block-definitions) are\nmixed in to block objects, the keyword `this` refers to the actual block\nbeing created.\n\nBoth methods result in a block definition object being stored in\n`Blockly.Blocks` with a key of the block type name (`string_length`). The block\ndefinition object has a single method (`init`), which defines the block's shape.\n\nMix JSON and JavaScript\n-----------------------\n\nThe JSON format primarily supports defining the look and feel of a block. It\ncannot directly define some features, such as validators and mutators, which\nrequire you to define a function. To solve this problem, define as much of your\nblock with JSON as possible, and use JavaScript for the rest.\n\nThe following example creates a block definition with an `init` function, which\nuses `jsonInit` to load a JSON object and the JavaScript API to define a dynamic\ntooltip. \n\n### JavaScript\n\n // Define the block structure in JSON.\n var mathChangeJson = {\n \"message0\": \"change %1 by %2\",\n \"args0\": [\n {\"type\": \"field_variable\", \"name\": \"VAR\", \"variable\": \"item\", \"variableTypes\": [\"\"]},\n {\"type\": \"input_value\", \"name\": \"DELTA\", \"check\": \"Number\"}\n ],\n \"previousStatement\": null,\n \"nextStatement\": null,\n \"colour\": 230\n };\n\n Blockly.Blocks['math_change'] = {\n init: function() {\n // Use jsonInit to load the JSON block structure.\n this.jsonInit(mathChangeJson);\n\n // Use JavaScript to define a tooltip function.\n // Assign 'this' to a variable for use in the tooltip closure below.\n var thisBlock = this;\n this.setTooltip(function() {\n return 'Add a number to variable \"%1\".'.replace('%1',\n thisBlock.getFieldValue('VAR'));\n });\n }\n };\n\nBlock definition API\n--------------------\n\nThis section summarizes the objects and functions used to define custom blocks.\n\n### Blockly.Blocks\n\n[`Blockly.Blocks`](/blockly/reference/js/blockly.blocks_variable) is an object\nthat stores block definitions. Its keys are block type names and its values are\nblock definition objects. Use `Blockly.Blocks` when defining blocks with\nJavaScript: \n\n Blockly.Blocks['my_block'] = {\n init: function() {/* ... */},\n onchange: function() {/* ... */},\n // ...\n }\n\nA common error is to assume `Blockly.Blocks` stores blocks and try something\nlike the following. This fails because `Blockly.Blocks` stores block\ndefinitions, not blocks. \n\n // Fails with \"Blockly.Blocks.my_block.setColour is not a function\".\n Blockly.Blocks['my_block'].setColour(150);\n\n### defineBlocksWithJsonArray\n\n[`defineBlocksWithJsonArray`](/blockly/reference/js/blockly.common_namespace.defineblockswithjsonarray_1_function)\naccepts an array of JSON objects, creates block definitions from them, and adds\nthem to `Blockly.Blocks`. \n\n Blockly.common.defineBlocksWithJsonArray([\n {\n type: 'my_block1',\n // ...\n }\n {\n type: 'my_block3',\n // ...\n }\n {\n type: 'my_block2',\n // ...\n }\n ]);\n\n### createBlockDefinitionsFromJsonArray and defineBlocks\n\n[`createBlockDefinitionsFromJsonArray`](/blockly/reference/js/blockly.common_namespace.createblockdefinitionsfromjsonarray_1_function)\naccepts an array of JSON objects and returns an object that maps block type\nnames to block definitions. This is generally used with `defineBlocks`, which\nadds the block definitions to `Blockly.Blocks`. \n\n const myBlockDefinitions = Blockly.common.createBlockDefinitionsFromJsonArray([\n {\n type: 'my_block1',\n // ...\n }\n {\n type: 'my_block3',\n // ...\n }\n {\n type: 'my_block2',\n // ...\n }\n ]);\n Blockly.common.defineBlocks(myBlockDefinitions);\n\n### Block.jsonInit\n\n[`jsonInit`](/blockly/reference/js/blockly.block_class.jsoninit_1_method)\naccepts a JSON object and calls the corresponding methods on `Block`. For\nexample, a JSON object with the key-value pair `colour: 150` results in a call\nto `this.setColour(150)`. Use `jsonInit` in an `init` function to load a JSON\nobject. \n\n var myJson = {\n // ...\n };\n\n Blockly.Blocks['my_block'] = {\n init: function() {\n this.jsonInit(myJson);\n // The rest of the init function.\n }\n };"]]