Kostyuk Rostyslav
Kostyuk Rostyslav

Reputation: 417

Aframe component can't reference el from event handler

I am trying to write a game using lance-gg library. I tried to implement a simple aframe component, that print entity's object3D position and rotation in world space. The problem is that I cannot access this from within the component event listener.

I have tried to search around I've found this [thread] (Aframe unregister component), so I guess the problem is the initialization order. I have tried to include a component directly from the index but it does't worked either.

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

this component was created in a separate file called aSeparateFile.js, I include this file from my AFrameRenderer extension. Like this:

import {AFRAMERenderer} from 'lance-gg';

import './aSeparateFile.js';

I would like to know the best way to register a custom component with lance-gg.

Upvotes: 2

Views: 246

Answers (1)

Diego Marcos
Diego Marcos

Reputation: 4585

Don't use arrow functions that will bind the methods to the wrong this. Use regular functions instead:

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

Upvotes: 2

Related Questions