跨组件中的函数访问事件侦听器数据

accessing event listener data across functions in a component

我试图在 aframe 组件的另一个函数中访问从 init() 中的事件侦听器函数获取的数据。我尝试过使用绑定,以便事件监听器中获取的数据可以绑定到“this”space.

这是我的代码

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
  }

});

我想如果我将它绑定到函数,我也可以访问 even 侦听器范围之外的数据。你能抽出一点时间帮我解决这个问题吗?

原因是您修改的变量(speed)超出范围。由于您在函数 init 中声明了一个新函数 testfun,它具有自己的属性。 如果你可以使用 ES5+ 语法,那么你可以将 testfun 声明为箭头函数,这样你就完成了。 有关更多信息,请阅读此处:https://zendev.com/2018/10/01/javascript-arrow-functions-how-why-when.html

试试这个:

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

这是预期的行为。您可能没有意识到,在您的 console.log 调用之后,事件会在任意时间触发。到 init 运行时 this.speed 尚未初始化。您必须等到 gameStarted 事件触发才能获取值。 tick 在事件触发之前也是如此。给 this.speed 一个初始值以避免 undefined

AFRAME.registerComponent('move', {
  schema: {    
  },

  init: function() { 
    var self = this;   
    this.speed = 0;
    this.el.sceneEl.addEventListener('gameStarted', testfun.bind(this), {once: 
    true});

    function testfun(e){      
        self.speed = e.detail.source;
        console.log(self.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
  }