4. Registering Custom Components

Vivek Chandela
YoungSphere
Published in
2 min readSep 18, 2020

This is a series on using WebXR to build immersive content. To access the other blogs in the series, follow this link.

Let us take “foo” as the name of our custom component. There are 2 ways to do register custom components in your project:

1. Create a new file foo.js

Now add the following code to it:

AFRAME.registerComponent('foo', {
schema: {
bar: {type: 'number'},
baz: {type: 'string'}
},

init: function () {
// Do something when the component is first attached.
},

update: function () {

// Do something when the component's data is updated.
},

remove: function () {
// Do something when the component or its entity is detached.
},

tick: function (time, timeDelta) {
// Do something on every scene tick or frame.
}
});

Entity-component framework gives us the ability to write a JavaScript module and abstract it through HTML. Once the component is registered, we can declaratively plug this module of code into an entity via an HTML attribute.

To use this component, add a <script> inside <head>:

<script src=”foo-component.js”></script>

2. Register the component inside index.html using a <script> before the <a-scene>

Using this, you can avoid importing a JS file but this approach reduces code readability.

<html>
<head>
<script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
</head>
<body>
<script>
// inline before the <a-scene>.
AFRAME.registerComponent('foo', {
// ...
});
</script>

<a-scene> <a-entity foo="bar: 5; baz: bazValue"></a-entity>
</a-scene>
</body>

</html>

So, foo is the name of the component we just registered, and the data contains bar and baz properties. Now, we can add this component inside <a-scene> to use it in our code.

<a-scene><a-entity foo="bar: 5; baz: bazValue"></a-entity></a-scene>

This is just a preview on how to write a basic component. We’ll see it in more detail later. Meanwhile, you can read more about it here.

In the next blog, we’ll learn how to add 3D models to our project.

See you in the next one.

YoungSphere crowdsources immersive content for K12 education. Contribute your AR/VR content at www.youngsphere.com to earn monetary credits.

--

--

Vivek Chandela
YoungSphere

I know a little bit of some topics through a combo of curiosity + FOMO