Javascript 如何在块自定义块的“onchange”事件中获取值?
我正在为Blockly制作一个自定义块,需要验证输入。在Javascript 如何在块自定义块的“onchange”事件中获取值?,javascript,blockly,Javascript,Blockly,我正在为Blockly制作一个自定义块,需要验证输入。在onchange事件中,如果用户输入的输入值无效,我想警告用户 这是我的街区: Blockly.Blocks['motor'] = { init: function() { this.setHelpUrl('http://www.example.com/'); this.setColour(65); this.appendDummyInput() .append
onchange
事件中,如果用户输入的输入值无效,我想警告用户
这是我的街区:
Blockly.Blocks['motor'] = {
init: function() {
this.setHelpUrl('http://www.example.com/');
this.setColour(65);
this.appendDummyInput()
.appendField("motor( ");
this.appendValueInput("port_number")
.setCheck("Number");
this.appendDummyInput()
.appendField(");");
this.setInputsInline(true);
this.setPreviousStatement(true);
this.setNextStatement(true);
this.setTooltip('');
},
onchange: function(ev) {
if (this.getFieldValue('port_number') > '3') {
this.setWarningText('Port must be 0 - 3.');
} else {
this.setWarningText(null);
}
}
};
在上,它有一个获取输入值的基本示例。但是,每次触发onchange
时,我都会得到一个undefined
返回
如何处理这些输入的验证?我不想为输入创建下拉列表,因为我需要能够从变量、int块等进行输入。不确定这是否是处理此问题的最佳方法,但它对我很有效。我只是使用
valueToCode
方法访问输入值。然后我可以验证输入值
注意:onchange
处理程序的上下文是块,因此传递
此
作为Blockly的第一个参数。C.valueToCode
将获得
来自正确块的值
试试这个:
this.getInputTargetBlock('port_number').toString()
或:
例如:
Blockly.Blocks['stop_actions'] = {
init: function() {
var actions_descriptors = [
['HOLD', 'hold'],
['COAST', 'coast']
];
this.appendDummyInput()
.appendField(new Blockly.FieldDropdown(actions_descriptors), 'action')
.setAlign(Blockly.ALIGN_RIGHT);
this.setOutput(true, 'String');
this.setColour(60);
this.setTooltip('Select the stop action');
}
};
Blockly.Blocks['motor'] = {
init: function() {
this.appendValueInput('arg_stop_action')
.appendField('Stop action')
.setAlign(Blockly.ALIGN_RIGHT);
},
onchange: function(e) {
this.getInputTargetBlock('arg_stop_action').getFieldValue('action')
}
};
你解决这个问题了吗?如果有,请邮寄。如果您没有,您可以随时执行console.log(此)以了解发生了什么;或者,最好设置一个断点并进行计算。或者,在某些情况下,您可以使用'var block=Blockly.selected`@ТаняТ. 感谢您的帮助,您的评论确实让我决定了如何提取输入值!您是否使用Blockly.selected?你知道你的
这个是什么吗。我不需要Blockly.selected,因为我已经有了块的实例这个
就是那个实例。
this.getInputTargetBlock('port_number').getFieldValue(/*field_name*/)
Blockly.Blocks['stop_actions'] = {
init: function() {
var actions_descriptors = [
['HOLD', 'hold'],
['COAST', 'coast']
];
this.appendDummyInput()
.appendField(new Blockly.FieldDropdown(actions_descriptors), 'action')
.setAlign(Blockly.ALIGN_RIGHT);
this.setOutput(true, 'String');
this.setColour(60);
this.setTooltip('Select the stop action');
}
};
Blockly.Blocks['motor'] = {
init: function() {
this.appendValueInput('arg_stop_action')
.appendField('Stop action')
.setAlign(Blockly.ALIGN_RIGHT);
},
onchange: function(e) {
this.getInputTargetBlock('arg_stop_action').getFieldValue('action')
}
};