JSON 및 JavaScript

Blockly에는 블록을 정의하는 두 가지 방법이 있습니다. 키-값 쌍을 사용하는 JSON 객체와 Blockly의 API를 호출하는 JavaScript 함수입니다. JSON 형식은 현지화를 간소화하고 읽고 쓰기가 더 쉽기 때문에 선호됩니다. 그러나 이를 사용하여 변경자 또는 유효성 검사기와 같은 고급 기능을 직접 정의할 수는 없습니다. 이러한 기능은 일반적으로 확장 프로그램으로 JavaScript로 작성해야 합니다.

JSON 또는 JavaScript 사용

이 블록:

`string_length` 블록

다음과 같이 JSON 또는 JavaScript로 정의할 수 있습니다.

JSON

Blockly.common.defineBlocksWithJsonArray([{
  "type": "string_length",
  "message0": 'length of %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는 각 JSON 객체를 블록 정의 객체 와 함께 init 함수로 변환합니다. 이러한 객체를 Blockly.Blocks에 저장합니다.

JavaScript

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 함수가 있는 블록 정의를 만듭니다.

JavaScript

// Define the block structure in JSON.
var mathChangeJson = {
  "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.
    var thisBlock = this;
    this.setTooltip(function() {
      return 'Add a number to variable "%1".'.replace('%1',
          thisBlock.getFieldValue('VAR'));
    });
  }
};

블록 정의 API

이 섹션에서는 커스텀 블록을 정의하는 데 사용되는 객체와 함수를 요약합니다.

Blockly.Blocks

Blockly.Blocks 는 블록 정의를 저장하는 객체입니다. 키는 블록 유형 이름이고 값은 블록 정의 객체입니다. JavaScript로 블록을 정의할 때는 Blockly.Blocks를 사용하세요.

Blockly.Blocks['my_block'] = {
  init: function() {/* ... */},
  onchange: function() {/* ... */},
  // ...
}

일반적인 오류는 Blockly.Blocks가 블록을 저장한다고 가정하고 다음과 같은 작업을 시도하는 것입니다. Blockly.Blocks는 블록이 아닌 블록 정의를 저장하므로 이 작업은 실패합니다.

// Fails with "Blockly.Blocks.my_block.setColour is not a function".
Blockly.Blocks['my_block'].setColour(150);

defineBlocksWithJsonArray

defineBlocksWithJsonArray 는 JSON 객체 배열을 허용하고, JSON 객체 배열에서 블록 정의를 만든 후 Blockly.Blocks에 추가합니다.

Blockly.common.defineBlocksWithJsonArray([
  {
    type: 'my_block1',
    // ...
  }
  {
    type: 'my_block3',
    // ...
  }
  {
    type: 'my_block2',
    // ...
  }
]);

createBlockDefinitionsFromJsonArray 및 defineBlocks

createBlockDefinitionsFromJsonArray 는 JSON 객체 배열을 허용하고 블록 유형 이름을 블록 정의에 매핑하는 객체를 반환합니다. 일반적으로 블록 정의를 Blockly.Blocks에 추가하는 defineBlocks와 함께 사용됩니다.

const myBlockDefinitions = Blockly.common.createBlockDefinitionsFromJsonArray([
  {
    type: 'my_block1',
    // ...
  }
  {
    type: 'my_block3',
    // ...
  }
  {
    type: 'my_block2',
    // ...
  }
]);
Blockly.common.defineBlocks(myBlockDefinitions);

Block.jsonInit

jsonInit 는 JSON 객체를 허용하고 Block에서 해당 메서드를 호출합니다. 예를 들어 키-값 쌍 colour: 150이 있는 JSON 객체는 this.setColour(150) 호출을 생성합니다. init 함수에서 jsonInit를 사용하여 JSON 객체를 로드합니다.

var myJson = {
  // ...
};

Blockly.Blocks['my_block'] = {
  init: function() {
    this.jsonInit(myJson);
    // The rest of the init function.
  }
};