首页 > 解决方案 > JSXGraph:事件绑定中类方法的调用

问题描述

我想定义一个用于 JSXGraph 小部件的对象,它可以在鼠标单击时激活或停用(现在只是切换可见性和“固定”属性)。

我定义了方法activate() 和deactivate()。这些可以从构造方法中调用(根据参数设置初始状态)。但是我无法将方法绑定到鼠标事件。

知道什么可能导致问题或如何正确解决任务吗?

     this.graph = board.create('functiongraph' [ 
       JXG.Math.Numerics.hermitePolynomial(this.p1, this.p2, this.pt1, this.pt2, 
         this.t1, this.t2),
       this.p1.X(), this.p2.X() ],
       { strokecolor: 'red', strokewidth: 3 });
    // set activate/deactivate, this works
    this.obj = [ this.p1, this.p2, this.pt1, this.pt2, this.t1, this.t2 ];
    if (this.state == "active") { this.activate() }
    else {this.deactivate() }
    
    //switch by mouseclick, this doesn't work
    this.graph.on('down', function() {
      if (this.state == "active") { 
        console.log("deactivate", this.obj); this.deactivate(); }
      else {  console.log("activate"); this.activate(); }
      } )
  }
  activate() {console.log("activate"); this.state = "active";
        for (var part of this.obj) {
          part.setAttribute({visible:true});
          part.setAttribute({fixed:false});
        } update()}
  deactivate() {console.log("deactivate"); this.state = "inactive";
        for (var part of this.obj) {
          part.setAttribute({visible:false});
          part.setAttribute({fixed:true});
        } update()}

在这个例子中,右边的红色样条线应该可以通过鼠标点击来切换。

然而单击它们会导致错误

未捕获的 TypeError:this.activate 不是函数

这个我没看懂,因为在代码上面直接调用方法就可以成功了。

jsfiddle上的完整示例

标签: eventsmousejsxgraph

解决方案


我自己找到了解决方案。问题是鼠标绑定中的“this”指的是对象,绑定被应用到。在这种情况下,它是一个图形对象。

如果我想访问父对象的方法,我可以定义该对象的父属性并通过“this.parent.method()”访问该方法

我可能实现它有点过于复杂,但它现在可以工作了。

this.graph = board.create('functiongraph', [hermiteplot(this.P,this.p1, this.p2, this.pt1, this.pt2), this.p1.X(), this.p2.X()], { strokecolor: 'red', strokewidth: 3  });
    // set activate/deactivate
        this.obj = [ this.p1, this.p2, this.pt1, this.pt2 ];
    if (this.state == "active") { this.activate(this) }
    if (this.state == "inactive") { this.deactivate(this) }
    if (this.state == "locked") { this.deactivate(this); this.state = "locked" }
    
    //switch by doubleclick
    this.graph.parent = this;
    this.graph.lastclick = Date.now();    
    this.graph.on('up', function() {
      if (Date.now()-this.lastclick < 500) {console.log(this.parent.state); this.parent.switch()}
      else {this.lastclick = Date.now() }})
  }
  switch() {if (this.state == "active") { this.deactivate(this)}
      else if (this.state == "inactive") { this.activate(this);}
      console.log(this.state)}
  activate(ref) {console.log("this.activate()"); ref.state = "active";
        for (var part of ref.obj) {
          part.setAttribute({visible:true});
          part.setAttribute({fixed:false});
        } update()}
  deactivate(ref) {console.log("this.deactivate()"); ref.state = "inactive";
        for (var part of ref.obj) {
          part.setAttribute({visible:false});
          part.setAttribute({fixed:true});
        } update()}

jsfiddle


推荐阅读