Search code examples
aframe

Alter component on enter-vr event


I'm working on my scrim component for A-Frame and want it to "turn off" when VR Mode is entered. Where in the component can I listen for the enter-vr event so I can remove animations?

I add animation settings for opacity on init of the component. I don't know where add a listener for enter-vr to remove the added animation.

  init: function () {
    var thisEl = this.el;
    var data = this.data

    var properties = 'property: material.opacity; from: 0; to: 1; dir: alternate; loop: true'
    properties = properties.concat(properties,'; dur: ', data.durration, '; easing: ', data.easing)

    thisEl.setAttribute('animation', properties)

    document.querySelector('a-scene').addEventListener('enter-vr', remove())

  },

  remove: function () {
    var thisEl = this.el;

    thisEl.setAttribute('animation', '')
   },

I expected the listener in the init function to call the remove function when enter-vr fires.


Solution

  • The method is not correctly attached. Try this instead:

    document.querySelector('a-scene').addEventListener('enter-vr', this.remove.bind(this));
    

    Your code is calling the function and passing the result to addEventListener not a reference to the function itself. I recommend reading about function declarations, statements and scoping in JavaScript for better understanding.

    Also to remove a component use removeAttribute:

    thisEl.removeAttribute(“animation”);
    

    With setAttribute you are setting the properties to the default values not removing the component. Additional info in docs: https://aframe.io/docs/0.9.0/introduction/javascript-events-dom-apis.html#removing-a-component-with-removeattribute