events - 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 不是函数
这个我没看懂,因为在代码上面直接调用方法就可以成功了。
解决方案
我自己找到了解决方案。问题是鼠标绑定中的“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()}
推荐阅读
- python - 通过 groupby 连接 pandas 数据框
- android - MvvmCross 和 Android 通知
- javascript - CSS可以通过像素映射来变形图像吗?
- javascript - “Web 的交互式数据可视化”中的回调函数变量顺序
- batch-file - 使用带有可变跳过字符的可变子字符串
- c# - 为什么我的字符串没有转换为整数?
- react-native - React Native Maps 组件在后台运行时无法关闭位置跟踪
- sql - 通过将值拆分为三个字符块来生成行
- javascript - 如何为元素添加 `for=""` 和 `required=''` 属性?
- java - 如何在不同表中没有重复记录的情况下进行休眠保存