擴充功能和混合函式

擴充功能是指在初始化期間在區塊上執行的函式。這些通常會在區塊中加入一些自訂設定或行為Mixin 可讓您將屬性或輔助函式新增至區塊,但不會立即執行。

只有在使用 JSON 定義區塊時,才需要使用擴充功能或混合函式。如果您使用 JavaScript 定義區塊,可以在 init 中直接呼叫初始化函式,並直接將方法或屬性新增至定義。

額外資訊

擴充功能是指在建立區塊時,在每個特定類型的區塊上執行的函式。舉例來說,他們可能會新增自訂設定 (例如設定區塊的工具提示) 或自訂行為 (例如在區塊中新增事件監聽器)。

// This extension sets the block's tooltip to be a function which displays
// the parent block's tooltip (if it exists).
Blockly.Extensions.register(
    'parent_tooltip_extension',
    function() { // this refers to the block that the extension is being run on
      var thisBlock = this;
      this.setTooltip(function() {
        var parent = thisBlock.getParent();
        return (parent && parent.getInputsInline() && parent.tooltip) ||
            Blockly.Msg['MATH_NUMBER_TOOLTIP'];
      });
    });

擴充功能必須「註冊」,才能與字串鍵建立關聯。接著,您可以將這個字串鍵指派給區塊類型的 JSON 定義extensions 屬性,將擴充功能套用至區塊。

{
 //...,
 "extensions": ["parent_tooltip_extension",]
}

您也可以一次新增多個擴充功能。請注意,即使您只套用一個擴充功能,extensions 屬性也必須是陣列。

{
  //...,
  "extensions": ["parent_tooltip_extension", "break_warning_extension"],
}

Mixin

如果您想在區塊中加入一些屬性/輔助函式,但不立即執行,Blockly 也提供方便的方法。這項功能可讓您註冊包含所有額外屬性/方法的 mixin 物件。接著,mixin 物件會包裝在函式中,每次建立指定區塊類型的例項時,就會套用 mixin。

Blockly.Extensions.registerMixin('my_mixin', {
  someProperty: 'a cool value',

  someMethod: function() {
    // Do something cool!
  }
))`

與混合內容相關聯的字串鍵可在 JSON 中參照,就像其他擴充功能一樣。

{
 //...,
 "extensions": ["my_mixin"],
}