Search code examples
javascriptaframe

Restarting entire A-Frame component from if / else


Edit 2: Turns out you can specify the duration of the tick function so it acts as a timed refresh (quite useful). The number is in milliseconds and this 'tick' replaces the 'init' at the beginning of the component registration.

tick: function () {
    this.tick = AFRAME.utils.throttleTick(this.tick, 8000, this);

Edit: Thanks to Piotr the setAttribute("world"," ") call does indeed work. In my case I used .setAttribute('truefalse', '') though (truefalse being the name of my registered component). Unfortunately it only works for a single loop though. I'm not sure what could be done to make it re-update every time the condition is met.

ORIGINAL: There is a Javascript component in my A-Frame that has a lot of code inside which I want to refresh near the end when an 'if / else' condition is met. I already have everything running, but cant figure out how to use the else { declaration to restart the initial AFRAME.registerComponent('world', { init: function () {

Should I be using a update: function () {, or something like that, or do I have to use some kind of 'for loop' code? I'm sure this is a very common question so I'm sorry if it has been asked a lot already.


Solution

  • AFRAME.registerComponent("world", {
      init: function() {
        /*here you do what you want to be done once, 
        for example add event listeners */
      },
      update: function() {
        /* this function will run every time components will receive new data */ 
      }, 
      tick: function() {
        /* this function will run on every frame.
           Be frugal with creating objects here -
           too much objects will result in poor performance */
    
      },
      myCustomFunction: function() {
      }
    });
    

    If myCustomFunction is what you want to do on every tick, use:

    tick: function() {
      this.myCustomFunction();
    }
    

    If myCustomFunction is what you want to do on every time component receives new data, use:

    update: function() {
      this.myCustomFunction();
    }
    

    Update after reading comments:

    tick: function() {
      if(.....) {
        ...
        this.update();
      } else {
        ...
      }
    }