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

时间:2015-10-29 11:13:42

标签: javascript visual-programming blockly

我正在以块状方式工作,我有一个场景,我正在拥有一个有图像的块,我想点击该图像并触发一个事件。我不知道怎么能这样做。我试过blcokly的文档,但没有提到。它们只在整个块上提供onchange事件,而Image只是该块的一部分。

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

提前致谢。

1 个答案:

答案 0 :(得分:3)

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

describe('method: reset()', function(){
  it('should reset the Context variable', function(){
    spyOn(Tag, 'reset').andCallFake(function(){
      return Context;
    });

    expect(Context).toEqual({});
  });

  afterEach(function(){
    if(Context!== {}){
      Context = {};
    }
  })
});

在块之后,你必须添加myFieldImage而不是使用fieldImage。并且将从块传递isClickListener参数。以下是代码 -

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); 
  }

};