如何在 blockly 的块中添加点击事件?

how to add a click event in blockly's blocks?

我正在处理块,我有一个场景,我有一个块有一个图像,我想点击那个图像并触发一个事件。我不确定我该怎么做。我试过 blcokly 的文档,但没有这样的提及。他们只在整个块上提供 onchange 事件,而图像将只是该块的一部分。

任何想法我怎样才能做到这一点?

提前致谢。

我有扩展 field_image.js 文件的想法,我继承了必要的文件,并且在 init 函数中我在 SVG 元素中添加了一个 eventlistenr。这就是我使图像可点击的方式。以下是代码-

MyFieldImage.prototype = new Blockly.FieldImage();
MyFieldImage.prototype.constructor = MyFieldImage;
function MyFieldImage(src, width, height, opt_alt,isClickListener){
    this.clickEventListener  = isClickListener;
    this.sourceBlock_ = null;
  // Ensure height and width are numbers.  Strings are bad at math.
  this.height_ = Number(height);
  this.width_ = Number(width);
  this.size_ = new goog.math.Size(this.width_,
      this.height_ + 2 * Blockly.BlockSvg.INLINE_PADDING_Y);
  this.text_ = opt_alt || '';
  this.setValue(src);
}

MyFieldImage.prototype.init = function(block) {
  if (this.sourceBlock_) {
    // Image has already been initialized once.
    return;
  }
  this.sourceBlock_ = block;
  // Build the DOM.
  /** @type {SVGElement} */
  this.fieldGroup_ = Blockly.createSvgElement('g', {}, null);
  if (!this.visible_) {
    this.fieldGroup_.style.display = 'none';
  }
  /** @type {SVGElement} */
  this.imageElement_ = Blockly.createSvgElement('image',
      {'height': this.height_ + 'px',
       'width': this.width_ + 'px'}, this.fieldGroup_);
  this.setValue(this.src_);
  if (goog.userAgent.GECKO) {
    /**
     * Due to a Firefox bug which eats mouse events on image elements,
     * a transparent rectangle needs to be placed on top of the image.
     * @type {SVGElement}
     */
    this.rectElement_ = Blockly.createSvgElement('rect',
        {'height': this.height_ + 'px',
         'width': this.width_ + 'px',
         'fill-opacity': 0}, this.fieldGroup_);
  }
  block.getSvgRoot().appendChild(this.fieldGroup_);

  // Configure the field to be transparent with respect to tooltips.
  var topElement = this.rectElement_ || this.imageElement_;
  topElement.tooltip = this.sourceBlock_;
  Blockly.Tooltip.bindMouseEvents(topElement);
  if(this.clickEventListener){
    this.imageElement_.addEventListener("click", callingClick); 
  }

};

在此之后的块中,您必须添加 myFieldImage 而不是使用 fieldImage。和 isClickListener 参数将从块中传递。以下是代码 -

Blockly.Blocks['MyBlock'] = {
          init: function() {

            this.appendDummyInput()
                .appendField(new MyFieldImage("https://www.gstatic.com/codesite/ph/images/star_on.gif", 15, 15, "*",true));
            this.setTooltip('');
            this.setHelpUrl('http://www.example.com/');
          }
        };