Search code examples
javascriptcomponentsaframe

getAttribute does not working with AFRAME.registerComponent


I'm trying to write an aframe component to get a value from the position attribute. But, curiously, when I use the console.log, it first shows {x:0, y:0, z:0}, but when I click, it shows other values (the values that I need {x:5, y:0, z:0}, but I can't get through my code).

Code:

AFRAME.registerComponent('mycomponent', {
  schema: {
    destination: {type: 'string', default:''}
  },
    
  update: function () {

    if(this.data.destination){
      let destinationEl = document.querySelector(this.data.destination);
      let positionEl = destinationEl.getAttribute('position');

      console.log(positionEl);
    }
  }
});

Console

enter image description here

Access the code running here.


Solution

  • This is expected. You're trying to access data from an entity that has not yet initialized. Entities initialize children first and top to bottom

    You can put the entity first in the DOM:

    <a-box id="obj2"></a-box>
    <a-box mycomponent="destination:#obj2;"></a-box>
    

    Make it a child:

    <a-box mycomponent="destination:#obj2;">
      <a-box id="obj2"></a-box>
    </a-box>
    

    Or wait for the entity to load, making code independent of the DOM structure.

    var self = this;
    if (destinationEl.hasLoaded) {
      this.printPosition();
    } else {
      destinationEl.addEventListener('loaded', function () {
        self.printPosition();
      });
    }      
     
    

    Corrected glitch

    Also make sure you're using latest A-Frame. 1.3.0 at the moment of writing this.