[英]Generate a custom Blockly block from a user-provided string without eval
I am converting a string into a Google Blockly block using JavaScript.我正在使用 JavaScript 将字符串转换为 Google Blockly 块。
The input string is something like "Hello %s World"
- where %s
defines a string input.输入字符串类似于
"Hello %s World"
——其中%s
定义了一个字符串输入。 I need to turn that into:我需要把它变成:
Blockly.Blocks['blockname'] = {
init: function() {
this.appendDummyInput()
.appendField("Hello ")
.appendField(new Blockly.FieldTextInput("input1"), "")
.appendField(" World");
}
};
But I'm not sure how to achieve this without using eval()
, and as the input string is from the user, I understand that using eval()
would not be a good idea.但是我不确定如何在不使用
eval()
情况下实现这一点,并且由于输入字符串来自用户,我知道使用eval()
不是一个好主意。
My current code is:我目前的代码是:
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
}
}
But I'm not quite sure how to create the Blockly code that I need, without building up the JavaScript in a string and then using eval()
at the end.但是我不太确定如何创建我需要的 Blockly 代码,而不是在字符串中构建 JavaScript,然后在最后使用
eval()
。
Could someone please assist me with this?有人可以帮助我吗?
You can create a custom generic block without any inputs like below -您可以创建一个没有任何输入的自定义通用块,如下所示 -
Blockly.Blocks['generic_block'] = {
init: function() {
this.jsonInit({
message0: '',
colour: '230'
});
}
};
Now you can create a new instance of this block though the code.现在您可以通过代码创建此块的新实例。 Based on your JS string parsing, you can create the inputs and the fields inside this block as below -
根据您的 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.