Leroy Leroy - 1 month ago 26
HTML Question

cannot register aframe component in js file

I am trying to register an aframe component in a js file which is included from the base html file.
The components are registered correctly when in the html inside script tags, but do not register when in the js file.

example of code in html:



<html lang="en-US">
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />

<head>
<meta charset="utf-8">
<title>Gravity Puzzle</title>
<meta name="description" content="">
<script src="dist/aframe-v0.3.0.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>

<body>
<a-scene id="scene">
<script>
AFRAME.registerComponent('mouse-click-listener', {
init: function () {
var el = this.el;
window.addEventListener('click', function () {
console.log("click");
el.emit('click', null, false);
});
}
});
</script>

<a-sky id="sky" color="#AAAACC"></a-sky>

<a-entity id="cameraRoot" mouse-click-listener position="2 0.5 2" rotation="0 225 0">
<a-entity id="myCamera" camera acceleration look-controls keyboard-controls>
</a-entity>
</a-entity>
</a-scene>
</body>

</html>





Example of code in the js file:



function initialise()
{
AFRAME.registerComponent('mouse-click-listener', {
init: function () {
console.log("registered");
var el = this.el;
window.addEventListener('click', function () {
console.log("click");
el.emit('click', null, false);
});
}
});
}

window.onload = initialise;





Note, the 'registered' text does not appear in the browser console.
What am I missing?

Answer

Best to place the script tag after A-Frame before the scene.

<head>
  <meta charset="utf-8">
  <title>Gravity Puzzle</title>
  <meta name="description" content="">
  <script src="dist/aframe-v0.3.0.js"></script>
  <script src="mycomponent.js></script>
</head>

And don't need to wrap or wait for load:

    AFRAME.registerComponent('mouse-click-listener', {
        init: function () {
            console.log("registered");
            var el = this.el;
            window.addEventListener('click', function () {
                console.log("click");
                el.emit('click', null, false);
            });
        }
    });
}