gpt4 book ai didi

javascript - A型帧 : Scaling a-box in EventListener: "this.el is undefined"

转载 作者:行者123 更新时间:2023-11-30 19:14:46 24 4
gpt4 key购买 nike

我想在 A-Frame (JS) 中设置一个 EventListener,用于监听“mouseenter”事件并重新缩放框。我从 this tutorial 获取了来源.每次我将光标移到框上时,EventListener 都会触发,但随后控制台会显示

TypeError: this.el is undefined

引用这行代码:

this.el.object3D.scale.copy(data.to);

这是代码:

<script src="https://aframe.io/releases/0.9.2/aframe.min.js"></script>
<script>
AFRAME.registerComponent('scale-on-mouseenter', {
schema: {
to: {default: '10 10 10', type: 'vec3'}
},

init: function () {
var data = this.data;
this.el.addEventListener('mouseenter', function () {
this.el.object3D.scale.copy(data.to);
});
}
});
</script>
...
<a-box position="0 2 -5" scale-on-mouseenter>
</a-box>

它还说:

core:schema:warn Default value `10 10 10` does not match type `vec3` in component `scale-on-mouseenter`

最佳答案

1) this.el 未定义

这是scope的问题. this 不引用同一个对象:

//....
init: function() {
// here this refers the component object
console.log(this)
this.el.addEventListener('event', function() {
// here this refers to this.el (as the object which has the listener added)
console.log(this)
//...


你创建一个引用数据对象的变量,你可以用 this.el 做同样的事情:

var el = this.el;
this.el.addEventListener('click', function() {
el.doSomething();

或者使用不改变作用域的 lambda:

this.el.addEventListener('click', e => {
this.el.doSomething();

2) 值与类型不匹配

vec3 需要一个向量:{x: 10, y: 10, z: 10} 而不是字符串 10 10 10

关于javascript - A型帧 : Scaling a-box in EventListener: "this.el is undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58114818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com