accessing event listener data across functions in a component












0














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?



Thanks,
Niraj










share|improve this question



























    0














    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?



    Thanks,
    Niraj










    share|improve this question

























      0












      0








      0







      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?



      Thanks,
      Niraj










      share|improve this question













      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?



      Thanks,
      Niraj







      javascript javascript-events addeventlistener aframe






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 27 '18 at 16:06









      Niraj

      8718




      8718
























          2 Answers
          2






          active

          oldest

          votes


















          1














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





          share|improve this answer























          • I attach the "move" component to the entity conditionally after the gamestarted event gets fired. I am using aframe-state component to achieve that. So, I am able to get the value of speed inside the even listener but not outside the scope which is what I am trying to achieve.
            – Niraj
            Dec 27 '18 at 19:41










          • I am not sure what's wrong but it is still not working. I tried the exact code that you have given. I am not getting the value of speed outside the testfun as 0 ( the initialized value)
            – Niraj
            Dec 28 '18 at 17:01










          • Read my answer below: by the time you access the variable the gameStarted event has not yet fired
            – Diego Marcos
            Dec 29 '18 at 21:19





















          1














          That’s expected behavior. You have probably not realized that events will fire at any arbitrary time, after your console.log calls. By the time init runs this.speed is not yet initialized. You have to wait until gameStarted event fires to get a value. The same goes for tick before the event fires. Give this.speed an initial value to avoid 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
          }





          share|improve this answer























          • Thank you Diego. Actually this component "move" is attached to the entity conditionally with the condition being the event gameStarted being fired. Therefore, the init function will get executed after that event has been fired. I achieve this conditional attachment/detachment using aframe-state component. I have now realised that attaching and detaching this component based on the event does not let me persist with the value of this.speed. I have now changed my code to remove this condition so now this issue is resolved. Thank you so much for your help.
            – Niraj
            2 days ago










          • If the event fires before init, it wont be captured either by testfun. You need to attach the eventlistener and then wait for the event to be fired. You should be able to store the variable in the component. I recommend familiarization with how javascript scoping works: css-tricks.com/javascript-scope-closures
            – Diego Marcos
            2 days ago













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53947786%2faccessing-event-listener-data-across-functions-in-a-component%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














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





          share|improve this answer























          • I attach the "move" component to the entity conditionally after the gamestarted event gets fired. I am using aframe-state component to achieve that. So, I am able to get the value of speed inside the even listener but not outside the scope which is what I am trying to achieve.
            – Niraj
            Dec 27 '18 at 19:41










          • I am not sure what's wrong but it is still not working. I tried the exact code that you have given. I am not getting the value of speed outside the testfun as 0 ( the initialized value)
            – Niraj
            Dec 28 '18 at 17:01










          • Read my answer below: by the time you access the variable the gameStarted event has not yet fired
            – Diego Marcos
            Dec 29 '18 at 21:19


















          1














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





          share|improve this answer























          • I attach the "move" component to the entity conditionally after the gamestarted event gets fired. I am using aframe-state component to achieve that. So, I am able to get the value of speed inside the even listener but not outside the scope which is what I am trying to achieve.
            – Niraj
            Dec 27 '18 at 19:41










          • I am not sure what's wrong but it is still not working. I tried the exact code that you have given. I am not getting the value of speed outside the testfun as 0 ( the initialized value)
            – Niraj
            Dec 28 '18 at 17:01










          • Read my answer below: by the time you access the variable the gameStarted event has not yet fired
            – Diego Marcos
            Dec 29 '18 at 21:19
















          1












          1








          1






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





          share|improve this answer














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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 27 '18 at 19:50

























          answered Dec 27 '18 at 16:56









          jetblack

          1315




          1315












          • I attach the "move" component to the entity conditionally after the gamestarted event gets fired. I am using aframe-state component to achieve that. So, I am able to get the value of speed inside the even listener but not outside the scope which is what I am trying to achieve.
            – Niraj
            Dec 27 '18 at 19:41










          • I am not sure what's wrong but it is still not working. I tried the exact code that you have given. I am not getting the value of speed outside the testfun as 0 ( the initialized value)
            – Niraj
            Dec 28 '18 at 17:01










          • Read my answer below: by the time you access the variable the gameStarted event has not yet fired
            – Diego Marcos
            Dec 29 '18 at 21:19




















          • I attach the "move" component to the entity conditionally after the gamestarted event gets fired. I am using aframe-state component to achieve that. So, I am able to get the value of speed inside the even listener but not outside the scope which is what I am trying to achieve.
            – Niraj
            Dec 27 '18 at 19:41










          • I am not sure what's wrong but it is still not working. I tried the exact code that you have given. I am not getting the value of speed outside the testfun as 0 ( the initialized value)
            – Niraj
            Dec 28 '18 at 17:01










          • Read my answer below: by the time you access the variable the gameStarted event has not yet fired
            – Diego Marcos
            Dec 29 '18 at 21:19


















          I attach the "move" component to the entity conditionally after the gamestarted event gets fired. I am using aframe-state component to achieve that. So, I am able to get the value of speed inside the even listener but not outside the scope which is what I am trying to achieve.
          – Niraj
          Dec 27 '18 at 19:41




          I attach the "move" component to the entity conditionally after the gamestarted event gets fired. I am using aframe-state component to achieve that. So, I am able to get the value of speed inside the even listener but not outside the scope which is what I am trying to achieve.
          – Niraj
          Dec 27 '18 at 19:41












          I am not sure what's wrong but it is still not working. I tried the exact code that you have given. I am not getting the value of speed outside the testfun as 0 ( the initialized value)
          – Niraj
          Dec 28 '18 at 17:01




          I am not sure what's wrong but it is still not working. I tried the exact code that you have given. I am not getting the value of speed outside the testfun as 0 ( the initialized value)
          – Niraj
          Dec 28 '18 at 17:01












          Read my answer below: by the time you access the variable the gameStarted event has not yet fired
          – Diego Marcos
          Dec 29 '18 at 21:19






          Read my answer below: by the time you access the variable the gameStarted event has not yet fired
          – Diego Marcos
          Dec 29 '18 at 21:19















          1














          That’s expected behavior. You have probably not realized that events will fire at any arbitrary time, after your console.log calls. By the time init runs this.speed is not yet initialized. You have to wait until gameStarted event fires to get a value. The same goes for tick before the event fires. Give this.speed an initial value to avoid 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
          }





          share|improve this answer























          • Thank you Diego. Actually this component "move" is attached to the entity conditionally with the condition being the event gameStarted being fired. Therefore, the init function will get executed after that event has been fired. I achieve this conditional attachment/detachment using aframe-state component. I have now realised that attaching and detaching this component based on the event does not let me persist with the value of this.speed. I have now changed my code to remove this condition so now this issue is resolved. Thank you so much for your help.
            – Niraj
            2 days ago










          • If the event fires before init, it wont be captured either by testfun. You need to attach the eventlistener and then wait for the event to be fired. You should be able to store the variable in the component. I recommend familiarization with how javascript scoping works: css-tricks.com/javascript-scope-closures
            – Diego Marcos
            2 days ago


















          1














          That’s expected behavior. You have probably not realized that events will fire at any arbitrary time, after your console.log calls. By the time init runs this.speed is not yet initialized. You have to wait until gameStarted event fires to get a value. The same goes for tick before the event fires. Give this.speed an initial value to avoid 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
          }





          share|improve this answer























          • Thank you Diego. Actually this component "move" is attached to the entity conditionally with the condition being the event gameStarted being fired. Therefore, the init function will get executed after that event has been fired. I achieve this conditional attachment/detachment using aframe-state component. I have now realised that attaching and detaching this component based on the event does not let me persist with the value of this.speed. I have now changed my code to remove this condition so now this issue is resolved. Thank you so much for your help.
            – Niraj
            2 days ago










          • If the event fires before init, it wont be captured either by testfun. You need to attach the eventlistener and then wait for the event to be fired. You should be able to store the variable in the component. I recommend familiarization with how javascript scoping works: css-tricks.com/javascript-scope-closures
            – Diego Marcos
            2 days ago
















          1












          1








          1






          That’s expected behavior. You have probably not realized that events will fire at any arbitrary time, after your console.log calls. By the time init runs this.speed is not yet initialized. You have to wait until gameStarted event fires to get a value. The same goes for tick before the event fires. Give this.speed an initial value to avoid 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
          }





          share|improve this answer














          That’s expected behavior. You have probably not realized that events will fire at any arbitrary time, after your console.log calls. By the time init runs this.speed is not yet initialized. You have to wait until gameStarted event fires to get a value. The same goes for tick before the event fires. Give this.speed an initial value to avoid 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
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 29 '18 at 21:11

























          answered Dec 27 '18 at 19:07









          Diego Marcos

          1,83521013




          1,83521013












          • Thank you Diego. Actually this component "move" is attached to the entity conditionally with the condition being the event gameStarted being fired. Therefore, the init function will get executed after that event has been fired. I achieve this conditional attachment/detachment using aframe-state component. I have now realised that attaching and detaching this component based on the event does not let me persist with the value of this.speed. I have now changed my code to remove this condition so now this issue is resolved. Thank you so much for your help.
            – Niraj
            2 days ago










          • If the event fires before init, it wont be captured either by testfun. You need to attach the eventlistener and then wait for the event to be fired. You should be able to store the variable in the component. I recommend familiarization with how javascript scoping works: css-tricks.com/javascript-scope-closures
            – Diego Marcos
            2 days ago




















          • Thank you Diego. Actually this component "move" is attached to the entity conditionally with the condition being the event gameStarted being fired. Therefore, the init function will get executed after that event has been fired. I achieve this conditional attachment/detachment using aframe-state component. I have now realised that attaching and detaching this component based on the event does not let me persist with the value of this.speed. I have now changed my code to remove this condition so now this issue is resolved. Thank you so much for your help.
            – Niraj
            2 days ago










          • If the event fires before init, it wont be captured either by testfun. You need to attach the eventlistener and then wait for the event to be fired. You should be able to store the variable in the component. I recommend familiarization with how javascript scoping works: css-tricks.com/javascript-scope-closures
            – Diego Marcos
            2 days ago


















          Thank you Diego. Actually this component "move" is attached to the entity conditionally with the condition being the event gameStarted being fired. Therefore, the init function will get executed after that event has been fired. I achieve this conditional attachment/detachment using aframe-state component. I have now realised that attaching and detaching this component based on the event does not let me persist with the value of this.speed. I have now changed my code to remove this condition so now this issue is resolved. Thank you so much for your help.
          – Niraj
          2 days ago




          Thank you Diego. Actually this component "move" is attached to the entity conditionally with the condition being the event gameStarted being fired. Therefore, the init function will get executed after that event has been fired. I achieve this conditional attachment/detachment using aframe-state component. I have now realised that attaching and detaching this component based on the event does not let me persist with the value of this.speed. I have now changed my code to remove this condition so now this issue is resolved. Thank you so much for your help.
          – Niraj
          2 days ago












          If the event fires before init, it wont be captured either by testfun. You need to attach the eventlistener and then wait for the event to be fired. You should be able to store the variable in the component. I recommend familiarization with how javascript scoping works: css-tricks.com/javascript-scope-closures
          – Diego Marcos
          2 days ago






          If the event fires before init, it wont be captured either by testfun. You need to attach the eventlistener and then wait for the event to be fired. You should be able to store the variable in the component. I recommend familiarization with how javascript scoping works: css-tricks.com/javascript-scope-closures
          – Diego Marcos
          2 days ago




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53947786%2faccessing-event-listener-data-across-functions-in-a-component%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Mossoró

          Error while reading .h5 file using the rhdf5 package in R

          Pushsharp Apns notification error: 'InvalidToken'