I've been trying to create a scene that allows a user to switch between cameras upon clicking a "swap button" entity. I created a smaller CodePen demo to present the setup. Clicking on the swap entity (the sphere, here) will move the cursor between the old and the newly activated camera entities. When it does this, it has to call the init handler again. However, I'm having difficulty preventing this from causing an dogpile of event listeners on the cursor.
For the demo, the print-onenter component logs whether the cursor's over the a-sphere/box/cylinder/plane. Yet every additional camera swap by clicking on the sphere results in an additional print-out between mouseenter events (and you have to click it twice after, presumably because the clicks to swap will be undone by the additional click--but in the process add a different even/odd amount of listeners enabling you to actually swap next [set of] click event). I tried to apply a .removeEventListener, and to move print-onenter's function handler into a global scope so .removeEventListener would see it (since I assume anon handlers are effectively treated as unique types and therefore not treated as a duplicate listener and ignored).
function listenerTest (event) {
console.log("Object Entered: " + event.detail.intersectedEl.nodeName);
};
AFRAME.registerComponent( 'print-onenter', {
init: function() {
console.log('Reinitialized print-onenter.');
this.el.addEventListener( 'mouseenter', listenerTest );
},
remove: function() {
console.log('Deinitialized print-onenter.');
this.el.removeEventListener( 'mouseenter', listenerTest );
}
} );
Nevertheless, the same problem persists. Any help would be greatly appreciated.
remove
handler isn't called if it's simply reparented? Maybe you have to fully detach it then reattach it. Currently don't have much events or tests doing re-parenting yet. – ngokevin