javascript - Aframe 组件无法从事件处理程序引用 el

标签 javascript aframe lance

我正在尝试使用 lance-gg 库编写游戏。 我尝试实现一个简单的 aframe 组件,用于打印实体在世界空间中的 object3D 位置和旋转。 问题是我无法从组件事件监听器中访问 this

我尝试四处搜索,找到了这个[线程]( Aframe unregister component ),所以我猜问题是初始化顺序。我尝试直接从索引包含一个组件,但它也不起作用。

// aSeparateFile.js

AFRAME.registerComponent(
    'custom-component',
    {
        schema: {
            controllerID: {
                type: 'string',
                default: 'none'
            }
        },
        init: () => {
            console.log('componet has been created');
            console.log(this);
        },
        tick: () => {

            console.log(this.el.object3D.rotation);
            console.log(this.el.object3D.position);
        }
    }
);

此组件是在名为 aSeparateFile.js 的单独文件中创建的,我从 AFrameRenderer 扩展中包含此文件。像这样:

import {AFRAMERenderer} from 'lance-gg';

import './aSeparateFile.js';

我想知道使用 lance-gg 注册自定义组件的最佳方法。

最佳答案

不要使用arrow functions这会将方法绑定(bind)到错误的 this。使用常规函数代替:

AFRAME.registerComponent(
'custom-component',
{
    schema: {
        controllerID: {
            type: 'string',
            default: 'none'
        }
    },
    init: function () {
        console.log('componet has been created');
        console.log(this);
    },
    tick: function () {
        console.log(this.el.object3D.rotation);
        console.log(this.el.object3D.position);
    }
});

关于javascript - Aframe 组件无法从事件处理程序引用 el,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58421696/

相关文章:

javascript - Lance Game 发送 "secret"数据给个别玩家

javascript - 从监听器获取信息并将其传送到游戏引擎的最佳方式是什么?

javascript - 使用 casper 进行实时聊天抓取(Youtube)。选择 polymer 元素的问题

javascript - A-Frame 4.0 entityEl.getObject3D ('mesh' );不回脸

aframe - 如何用A型框架制作无限地板?

javascript - 在标记检测 A 帧 AR.JS 上播放音频

javascript - 使用 javascript 与 jquery 隐藏元素

javascript - 使用 JSON.parse 和 JSON.stringify 克隆 JS 数组后,为什么数组的 "undefined"值转换为 "null"?

javascript - 带有Mustache和JS的动态HTML页面构建器