Search code examples
javascriptdom-eventsaddeventlisteneraframe

accessing event listener data across functions in a component


I am trying to access data obtained from an event listener function in init() in another function in an aframe component. I have tried to use binding so that the data obtained in the event listener can be bound to "this" space.

Here is my code

AFRAME.registerComponent('move', {
  schema: {    
  },
  
  init: function() {    
    
    this.el.sceneEl.addEventListener('gameStarted', testfun.bind(this), {once: 
    true});
    
    function testfun(e){      
        this.speed = e.detail.source;
        console.log(this.speed); // I get proper values here
    }
    console.log(this.speed);  // value is not updated and I only get "undefined"
  },

  tick: function(t, dt) {
    console.log(this.speed); // I get undefined
  }

});

I thought if I bind this to function, I can access the data outside the even listener scope as well. Could you please spare a little time to help me figure this out?


Solution

  • The reason is that the variable (speed) you are modifying is out of scope. Since you have declared a new function testfun with its own properties in function init. If you can use ES5+ syntax then you can declare testfun as an arrow function instead and you are done. For more read about here: https://zendev.com/2018/10/01/javascript-arrow-functions-how-why-when.html

    try this:

    AFRAME.registerComponent("move", {
      schema: {},
    
      init: function() {
        this.speed = 0;
        this.el.sceneEl.addEventListener("gameStarted", testfun, {
          once: true
        });
        const testfun = e => {
          this.speed = e.detail.source;
          console.log(this.speed); // I get proper values here
        };
        console.log(this.speed); // value is not updated and I only get "undefined"
      },
    
      tick: function(t, dt) {
        console.log(this.speed); // I get undefined
      }
    });