簡體   English   中英

從用戶提供的字符串生成自定義 Blockly 塊,無需 eval

[英]Generate a custom Blockly block from a user-provided string without eval

我正在使用 JavaScript 將字符串轉換為 Google Blockly 塊。

輸入字符串類似於"Hello %s World" ——其中%s定義了一個字符串輸入。 我需要把它變成:

Blockly.Blocks['blockname'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Hello ")
        .appendField(new Blockly.FieldTextInput("input1"), "")
        .appendField(" World");
  }
};

但是我不確定如何在不使用eval()情況下實現這一點,並且由於輸入字符串來自用戶,我知道使用eval()不是一個好主意。

我目前的代碼是:

currentLine = blockText[x].split(/(%s)/);
for( var y = 0; y < currentLine.length; y++ )
{
  if( currentLine[y] == "" )
  {
    //do nothing
  }
  else if( currentLine[y] == "%s" )
  {
    //create a input
  }
  else
  {
    //create a label
  }
}

但是我不太確定如何創建我需要的 Blockly 代碼,而不是在字符串中構建 JavaScript,然后在最后使用eval()

有人可以幫助我嗎?

您可以創建一個沒有任何輸入的自定義通用塊,如下所示 -

  Blockly.Blocks['generic_block'] = {
    init: function() {
      this.jsonInit({
        message0: '',
        colour: '230'
      });
    }
  };

現在您可以通過代碼創建此塊的新實例。 根據您的 JS 字符串解析,您可以在此塊內創建輸入和字段,如下所示 -

var lineBlock=yourBlocklyWorkspace.newBlock('generic_block');         // create new instance of generic block
var input=lineBlock.appendDummyInput();                               // create a dummy input
var blockText="Hello %s World";                                       // one line of the JS code
var currentLine = blockText.split(/(%s)/);                            // split every word
for( var y = 0; y < currentLine.length; y++ ) {                       // loop through each word
  if(currentLine[y]==='%s') {                                         // if the word is %s, then append input field
    input.appendField(new Blockly.FieldTextInput('input'+y));         // input+y is the name of the field
  } else {                                                                         // else just append label field
    var labelField=new Blockly.FieldLabel('label'+y);                         // label+y is the name of the field
    labelField.setValue(currentLine[y]);                                          // set the label value to the word
    input.appendField(labelField)
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM