建立自訂程序資料模型

程序會參照所有定義程序簽章 (名稱、參數和傳回) 的支援資料模型。@blockly/block-shareable-procedures 外掛程式提供的資料模型,是為了複製 Blockly 舊版內建程序方塊的行為而建構。

這包括您可能不希望自訂程序積木出現的某些行為,例如:

  • 不支援退貨類型
  • 所有參數都與全域變數相關聯

如要使用不同的行為,可以建立自己的自訂程序資料模型。

程序模型實作

程序資料模型必須實作 IProcedureModel 介面。

class MyProcedureModel {
  constructor(workspace, name, id) {
    this.workspace = workspace;
    this.name = name;
    this.id = id;

    // Note: construction should not add the model to the procedure map.
  },

  // Other methods are omitted for brevity...
}

參數模型實作

參數資料模型必須實作 IParameterModel 介面。

class MyParameterModel {
  constructor(workspace, name, id) {
    this.workspace = workspace;
    this.name = name;
    this.id = id;
  },

  setProcedureModel(model) {
    this.model =  model;
    return this;
  }

  // Other methods are omitted for brevity...
}

觸發變更

凡是會觸發程序模型變更的方法,都應一併呼叫 @blockly/block-shareable-procedures 外掛程式中的 triggerProceduresUpdate。這會對任何程序方塊呼叫 doProcedureUpdate,導致這些方塊重新算繪。

import {triggerProceduresUpdate} from '@blockly/block-shareable-procedures';

class MyProcedureModel {
  setName(name) {
    this.name = name;
    triggerProcedureUpdate();
    return this;
  }

  // Other methods are omitted for brevity...
}

class MyParameterModel {
  setName(name) {
    this.name = name;
    triggerProcedureUpdate();
    return this;
  }

  // Other methods are omitted for brevity...
}

事件

@blockly/block-shareable-procedures 外掛程式中的程序模型也會在程序修改時觸發事件。這樣一來,多個工作區就能保持同步,並共用程序模型。您也可以選擇是否要觸發事件。

反序列化

此外,每個類別都需要 static loadState 方法,才能支援還原序列化。

class MyProcedureModel {
  static loadState(state, workspace) {
    // Note that the procedure model should not deserialize parameters.
    // The deserializer will handle that.
    return new MyProcedureModel(workspace, state.name, state.id);
  }

  // Other methods are omitted for brevity...
}

class MyParameterModel {
  static loadState(state, workspace) {
    return new MyParameterModel(workspace, state.name, state.id);
  }

  // Other methods are omitted for brevity...
}