Blockly에는 블록을 정의하는 두 가지 방법이 있습니다. 키-값 쌍을 사용하는 JSON 객체와 Blockly의 API를 호출하는 JavaScript 함수입니다. JSON 형식은 현지화를 단순화하고 읽고 쓰기가 더 쉽기 때문에 선호됩니다. 그러나 변형자나 검사기와 같은 고급 기능을 직접 정의하는 데는 사용할 수 없습니다. 이러한 함수는 일반적으로 확장 프로그램으로 JavaScript로 작성해야 합니다.
JSON 또는 JavaScript 사용
이 블록은 다음을 실행합니다.
다음과 같이 JSON 또는 JavaScript에서 정의할 수 있습니다.
JSON
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"}]);
defineBlocksWithJsonArray은 init 함수를 사용하여 각 JSON 객체를 블록 정의 객체로 변환합니다. 이러한 객체를 Blockly.Blocks에 저장합니다.
자바스크립트
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');}};
블록 정의 객체는 블록 객체에 혼합되므로 키워드 this는 생성 중인 실제 블록을 나타냅니다.
두 메서드 모두 블록 정의 객체가 블록 유형 이름 (string_length)의 키로 Blockly.Blocks에 저장됩니다. 블록 정의 객체에는 블록의 도형을 정의하는 단일 메서드 (init)가 있습니다.
JSON과 JavaScript 혼합
JSON 형식은 주로 블록의 디자인을 정의하는 것을 지원합니다. 함수를 정의해야 하는 검사기 및 변수와 같은 일부 기능은 직접 정의할 수 없습니다. 이 문제를 해결하려면 블록을 최대한 JSON으로 정의하고 나머지는 JavaScript를 사용하세요.
다음 예에서는 jsonInit를 사용하여 JSON 객체를 로드하고 JavaScript API를 사용하여 동적 도움말을 정의하는 init 함수로 블록 정의를 만듭니다.
자바스크립트
// 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'));});}};
Block definition API
이 섹션에서는 맞춤 블록을 정의하는 데 사용되는 객체와 함수를 요약합니다.
Blockly.Blocks
Blockly.Blocks는 블록 정의를 저장하는 객체입니다. 키는 블록 유형 이름이고 값은 블록 정의 객체입니다. JavaScript로 블록을 정의할 때 Blockly.Blocks를 사용합니다.
[null,null,["최종 업데이트: 2025-07-25(UTC)"],[],[],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 };"]]